I was reading a SQL “cookbook” type reference, and I came across a statement that I has never come across before:
INSERT INTO table (col1, col2)
SELECT t.col1, 8
FROM table AS t
WHERE t.col2 = 5
UNION ALL
SELECT 8, 8
Now what confuses me is a number (in this example, 8) immediately following the SELECT statement. In my limited SQL experience, I have only come across SELECT queries that are followed by column names. Could somebody help me understand what this does? Thanks!
The
SELECT 8, 8does exactly what it appears to do; it returns a result set with 2 un-named columns each containing8– if you run just that statement yourself you’ll see exactly that.You are free to select literal values & expressions just as you are columns, function results etc;
The
UNION ALLmerges (non-duplicate) rows from the 1st table select with the result of the 2nd select so your inserting a single additional(8,8)row into the table.