views:

278

answers:

3

Selecting constants without referring to a table is perfectly legal in an SQL statement:

SELECT 1, 2, 3

The result set that the latter returns is a single row containing the values. I was wondering if there is a way to select multiple rows at once using a constant expression, something kind of:

SELECT ((1, 2, 3), (4, 5, 6), (7, 8, 9))

I would want something like the above that works and returns a result set with 3 rows and 3 columns.

+5  A: 

In PostgreSQL, you can do:

SELECT  *
FROM    (
        VALUES
        (1, 2),
        (3, 4)
        ) AS q (col1, col2)

In other systems, just use UNION ALL:

SELECT  1 AS col1, 2 AS col2
-- FROM    dual
-- uncomment the line above if in Oracle
UNION ALL
SELECT  3 AS col1, 3 AS col2
-- FROM    dual
-- uncomment the line above if in Oracle

In Oracle, SQL Server and PostgreSQL, you also can generate recordsets of arbitrary number of rows (providable with an external variable):

SELECT  level
FROM    dual
CONNECT BY
        level <= :n

in Oracle,

WITH    q (l) AS
        (
        SELECT  1
        UNION ALL
        SELECT  l + 1
        FROM    q
        WHERE   l < @n
        )
SELECT  l
FROM    q
-- OPTION (MAXRECURSION 0)
-- uncomment line above if @n >= 100

in SQL Server,

SELECT  l
FROM    generate_series(1, $n) l

in PostgreSQL.

Quassnoi
+9  A: 
SELECT 1, 2, 3
UNION ALL SELECT 4, 5, 6
UNION ALL SELECT 7, 8, 9
Dewfy
+1 For what I would do
Oded
Exactly what I wanted!
Blagovest Buyukliev
A: 

I like Quassnoi's solution, but it doesn't work if @n=0. So he should add: WHERE @n >= 1

Robin