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

Running out of memory? Learn how Redis Enterprise enables large dataset analysis with the highest throughput and lowest latency while reducing costs over 75%! 

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.

Running out of memory? Never run out of memory with Redis Enterprise databaseStart your free trial today.


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

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}