Selecting constants without referring to a table is perfectly legal in an SQL statement:
SELECT 1, 2, 3
The result set that the latter retu
In MySQL, you can do: values (1,2), (3, 4);
mysql> values (1,2), (3, 4);
+---+---+
| 1 | 2 |
+---+---+
| 1 | 2 |
| 3 | 4 |
+---+---+
2 rows in set (0.004 sec)
With MySQL 8, it is also possible to give the column names:
mysql> SELECT * FROM (SELECT 1, 2, 3, 4) AS dt (a, b, c, d);
+---+---+---+---+
| a | b | c | d |
+---+---+---+---+
| 1 | 2 | 3 | 4 |
+---+---+---+---+
Here a way to create custom rows directly with MySQL request SELECT
:
SELECT ALL *
FROM (
VALUES
ROW (1, 2, 3),
ROW (4, 5, 6),
ROW (7, 8, 9)
) AS dummy (c1, c2, c3)
Gives us a table dummy
:
c1 c2 c3
-------------
1 2 3
4 5 6
7 8 9
Tested with MySQL 8
For Microsoft SQL Server or PostgreSQL you may want to try this syntax
SELECT constants FROM (VALUES ('foo@gmail.com'), ('bar@gmail.com'), ('baz@gmail.com')) AS MyTable(constants)
You can also view an SQL Fiddle here: http://www.sqlfiddle.com/#!17/9eecb/34703/0
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
.
Here is how to do it using the XML features of DB2
SELECT *
FROM
XMLTABLE ('$doc/ROWSET/ROW' PASSING XMLPARSE ( DOCUMENT '
<ROWSET>
<ROW>
<A val="1" /> <B val="2" /> <C val="3" />
</ROW>
<ROW>
<A val="4" /> <B val="5" /> <C val="6" />
</ROW>
<ROW>
<A val="7" /> <B val="8" /> <C val="9" />
</ROW>
</ROWSET>
') AS "doc"
COLUMNS
"A" INT PATH 'A/@val',
"B" INT PATH 'B/@val',
"C" INT PATH 'C/@val'
)
AS X
;
Following bare VALUES
command works for me in PostgreSQL:
VALUES (1,2,3), (4,5,6), (7,8,9)