Over a million developers have joined DZone.

Shortcut for inserting constants into SQL tables

DZone's Guide to

Shortcut for inserting constants into SQL tables

· Database Zone
Free Resource

Check out the IT Market Clock report for recommendations on how to consolidate and replace legacy databases. Brought to you in partnership with MariaDB.

There are many times you might find yourself with a need to insert constant data into a SQL table using a hand written SQL statement. Here’s a shortcut to save you some time and typing to generate the necessary SQL.

Most insert statements take the form :
insert into some_table
("value 1","value 2","value 3","value 4");

In general it is pretty annoying having to list all the fields in the table since it usually involves looking them all up, or extracting the table field list in some way and manipulating that to get a comma separated list of fields.

Another option is to take advantage of the fact that you can feed an insert statement with a select statement as long as the field count matches and the field data types are compatible.

insert into some_table
(select field_a, field_b, field_c, field_d from some_other_table);

We can use this mechanism and write our own select statement as a set of constant values. We’ll use the Oracle syntax for this which requires us to select the constant values from the omnipresent dual.

insert into some_table
(select "value 1","value 2","value 3","value 4" from dual);
This little technique means we don’t have to list the field names and the only limitation is that we have to provide a value for each field in the table. This can be a problem if you have a lot of fields without values, although adding null to the list of values gets around that.

Interested in reducing database costs by moving from Oracle Enterprise to open source subscription?  Read the total cost of ownership (TCO) analysis. Brought to you in partnership with MariaDB.


Published at DZone with permission of Andy Gibson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}