7.7. Списки VALUES
Предложение VALUES
позволяет создать «постоянную таблицу», которую можно использовать в запросе, не создавая и не наполняя таблицу в БД. Синтаксис предложения:
VALUES ( выражение
[, ...] ) [, ...]
Для каждого списка выражений в скобках создаётся строка таблицы. Все списки должны иметь одинаковое число элементов (т. е. число столбцов в таблице) и соответствующие элементы во всех списках должны иметь совместимые типы данных. Фактический тип данных столбцов результата определяется по тем же правилам, что и для UNION
(см. Раздел 10.5).
Как пример:
VALUES (1, 'one'), (2, 'two'), (3, 'three');
вернёт таблицу из двух столбцов и трёх строк. Это равносильно такому запросу:
SELECT 1 AS column1, 'one' AS column2 UNION ALL SELECT 2, 'two' UNION ALL SELECT 3, 'three';
По умолчанию Postgres Pro назначает столбцам таблицы VALUES
имена column1
, column2
и т. д. Имена столбцов не определены в стандарте SQL и в другой СУБД они могут быть другими, поэтому обычно лучше переопределить имена списком псевдонимов, например так:
=> SELECT * FROM (VALUES (1, 'one'), (2, 'two'), (3, 'three')) AS t (num,letter); num | letter -----+-------- 1 | one 2 | two 3 | three (3 rows)
Синтаксически список VALUES
с набором выражений равнозначен:
SELECTсписок_выборки
FROMтабличное_выражение
и допускается везде, где допустим SELECT
. Например, вы можете использовать его в составе UNION
или добавить к нему определение_сортировки
(ORDER BY
, LIMIT
и/или OFFSET
). VALUES
чаще всего используется как источник данных для команды INSERT
, а также как подзапрос.
За дополнительными сведениями обратитесь к справке VALUES.
7.7. VALUES
Lists
VALUES
provides a way to generate a “constant table” that can be used in a query without having to actually create and populate a table on-disk. The syntax is
VALUES ( expression
[, ...] ) [, ...]
Each parenthesized list of expressions generates a row in the table. The lists must all have the same number of elements (i.e., the number of columns in the table), and corresponding entries in each list must have compatible data types. The actual data type assigned to each column of the result is determined using the same rules as for UNION
(see Section 10.5).
As an example:
VALUES (1, 'one'), (2, 'two'), (3, 'three');
will return a table of two columns and three rows. It's effectively equivalent to:
SELECT 1 AS column1, 'one' AS column2 UNION ALL SELECT 2, 'two' UNION ALL SELECT 3, 'three';
By default, Postgres Pro assigns the names column1
, column2
, etc. to the columns of a VALUES
table. The column names are not specified by the SQL standard and different database systems do it differently, so it's usually better to override the default names with a table alias list, like this:
=> SELECT * FROM (VALUES (1, 'one'), (2, 'two'), (3, 'three')) AS t (num,letter); num | letter -----+-------- 1 | one 2 | two 3 | three (3 rows)
Syntactically, VALUES
followed by expression lists is treated as equivalent to:
SELECTselect_list
FROMtable_expression
and can appear anywhere a SELECT
can. For example, you can use it as part of a UNION
, or attach a sort_specification
(ORDER BY
, LIMIT
, and/or OFFSET
) to it. VALUES
is most commonly used as the data source in an INSERT
command, and next most commonly as a subquery.
For more information see VALUES.