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

RavenDB vs MongoDB: Which is Better? This White Paper compares the two leading NoSQL Document Databases on 9 features to find out which is the best solution for your next project.  

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.

Get comfortable using NoSQL in a free, self-directed learning course provided by RavenDB. Learn to create fully-functional real-world programs on NoSQL Databases. Register today.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}