Over a million developers have joined DZone.

Shortcut for inserting constants into SQL tables

· Database Zone

Sign up for the Couchbase Community Newsletter to stay ahead of the curve on the latest NoSQL news, events, and webinars. Brought to you in partnership with Coucbase.

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
(field1,field2,field3,field4)
values
("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.

The Getting Started with NoSQL Guide will get you hands-on with NoSQL in minutes with no coding needed. Brought to you in partnership with Couchbase.

Topics:

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

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

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

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

{{ parent.tldr }}

{{ parent.urlSource.name }}