A SELECT
without a FROM
clause gets us a multiple columns without querying a table:
SELECT 17+23, REPLACE('bannanna', 'nn', 'n'), RAND(), CURRENT_TIMESTAMP;
How can we write a query that results in multiple rows without referring to a table? Basically, abuse SELECT
to turn it into a data definition statement. The result could have a single column or multiple columns.
I'm most interested in a DBMS neutral answer, but others (e.g. based on UNPIVOT
) are welcome. I'd like to collect as many ways of doing this as possible. There's no technique application behind this question; it's more theoretical than practical.
T-SQL's
UNPIVOT
can transpose data from rows to columns. Multiple unpivots is equivalent to the Cartesian product of each unpivoted column.Result:
Use a UNION:
Looks like this in MySQL:
Use
UNION ALL
to avoid the loss of non-unique rows.You can use Table Value Constructors for this if supported by your RDBMS. Here's an example from Mr Celko