VALUES Clause in SQL Server
In SQL Server, VALUES is a table value constructor that specifies a set of row value expressions to be constructed into a table.
The VALUES clause is often used with INSERT statements to insert data, but it can also be used as a derived table in either the USING clause of the MERGE statement or the FROM clause.
Syntax
Note that DEFAULT is allowed only in an INSERT statement. DEFAULT forces SQL Server to insert the default value defined for the column. If a default does not exist for the column and the column allows null values, NULL is inserted. DEFAULT cannot be used on identity columns.
Examples
Here are some examples that demonstrate how VALUES can be used in SQL Server.
Used in an INSERT Statement
Here’s an example of using the VALUES clause as part of an INSERT statement:
That created a table called Idiots and inserted three rows into it.
We can now use a SELECT statement to see the new values in the table:
When the VALUES clause is used in an INSERT statement, there is a limit of 1000 rows. One way to overcome this is to use VALUES in a SELECT statement to create a derived table. That saves us from having to use multiple INSERT statements or doing a bulk insert.
Used in a SELECT Statement
We can use VALUES to create a derived table in the FROM clause. Here’s a SELECT statement to demonstrate:
Derived tables can be used to overcome the 1000 row limit when inserting values into a database.
Used in a MERGE Statement
Here’s an example of VALUES being used in a MERGE statement:
In this case, one row was updated and two new rows were inserted, based on the values provided in the VALUES clause.
Что такое values в sql
VALUES is a DML statement introduced in MySQL 8.0.19 which returns a set of one or more rows as a table. In other words, it is a table value constructor which also functions as a standalone SQL statement.
The VALUES statement consists of the VALUES keyword followed by a list of one or more row constructors, separated by commas. A row constructor consists of the ROW() row constructor clause with a value list of one or more scalar values enclosed in the parentheses. A value can be a literal of any MySQL data type or an expression that resolves to a scalar value.
ROW() cannot be empty (but each of the supplied scalar values can be NULL ). Each ROW() in the same VALUES statement must have the same number of values in its value list.
The DEFAULT keyword is not supported by VALUES and causes a syntax error, except when it is used to supply values in an INSERT statement.
The output of VALUES is a table:
The columns of the table output from VALUES have the implicitly named columns column_0 , column_1 , column_2 , and so on, always beginning with 0 . This fact can be used to order the rows by column using an optional ORDER BY clause in the same way that this clause works with a SELECT statement, as shown here:
In MySQL 8.0.21 and later, the VALUES statement also supports a LIMIT clause for limiting the number of rows in the output. (Previously, LIMIT was allowed but did nothing.)
The VALUES statement is permissive regarding data types of column values; you can mix types within the same column, as shown here:
VALUES with one or more instances of ROW() acts as a table value constructor; although it can be used to supply values in an INSERT or REPLACE statement, do not confuse it with the VALUES keyword that is also used for this purpose. You should also not confuse it with the VALUES() function that refers to column values in INSERT . ON DUPLICATE KEY UPDATE .
You should also bear in mind that ROW() is a row value constructor (see Section 13.2.15.5, “Row Subqueries”), whereas VALUES ROW() is a table value constructor; the two cannot be used interchangeably.
VALUES can be used in many cases where you could employ SELECT , including those listed here:
With UNION , as shown here:
You can union together constructed tables having more than one row, like this:
You can also (and it is usually preferable to) omit UNION altogether in such cases and use a single VALUES statement, like this:
VALUES can also be used in unions with SELECT statements, TABLE statements, or both.
The constructed tables in the UNION must contain the same number of columns, just as if you were using SELECT . See Section 13.2.18, “UNION Clause”, for further examples.
In MySQL 8.0.31 and later, you can use EXCEPT and INTERSECT with VALUES in much the same way as UNION , as shown here:
In joins. See Section 13.2.13.2, “JOIN Clause”, for more information and examples.
In place of VALUES() in an INSERT or REPLACE statement, in which case its semantics differ slightly from what is described here. See Section 13.2.7, “INSERT Statement”, for details.
In place of the source table in CREATE TABLE . SELECT and CREATE VIEW . SELECT . See the descriptions of these statements for more information and examples.
Что такое values в sql
VALUES — вычислить набор строк
Синтаксис
Описание
VALUES вычисляет значение строки или множество значений строк, заданное выражениями. Чаще всего эта команда используется для формирования « таблицы констант » в большой команде, но её можно использовать и отдельно.
Когда указывается больше, чем одна строка, все строки должны иметь одинаковое количество элементов. Типы данных результирующих столбцов таблицы определяются в результате совмещения явных и неявных типов выражений, заданных для этих столбцов, по тем же правилам, что и в UNION (см. Раздел 10.5).
В составе других команд синтаксис допускает использование VALUES везде, где допускается SELECT . Так как грамматически она воспринимается как SELECT , с командой VALUES можно использовать предложения ORDER BY , LIMIT (или равнозначное FETCH FIRST ) и OFFSET .
Параметры
Константа или выражение, которое вычисляется и вставляется в указанное место результирующей таблицы (множества строк). В списке VALUES , находящемся на верхнем уровне оператора INSERT , выражение может быть заменено словом DEFAULT , указывающим, что в целевой столбец должно быть вставлено значение этого столбца по умолчанию. Когда VALUES употребляется в других контекстах, указание DEFAULT использовать нельзя. выражение_сортировки
Выражение или целочисленная константа, указывающая, как должны сортироваться строки результата. Это выражение может обращаться к столбцам результата VALUES по именам column1 , column2 и т. д. За дополнительными подробностями обратитесь к разделу Предложение ORDER BY в описании SELECT . оператор
Оператор сортировки. За подробностями обратитесь к разделу Предложение ORDER BY в описании SELECT . число
Максимальное число строк, которое должно быть возвращено. За подробностями обратитесь к разделу Предложение LIMIT в описании SELECT . начало
Число строк, которые должны быть пропущены, прежде чем начнётся выдача строк. За подробностями обратитесь к разделу Предложение LIMIT в описании SELECT .
Замечания
Следует избегать составления списков VALUES с очень большим количеством строк, так как при этом можно столкнуться с нехваткой памяти или снижением производительности. Применение VALUES в команде INSERT — особый случай (так как ожидаемые типы столбцов становятся известны из целевой таблицы команды INSERT и их не надо вычислять, сканируя весь список VALUES ), так что в этом контексте можно работать с гораздо более объёмными списками, чем в других.
Примеры
Простейшая команда VALUES :
Эта команда выдаст таблицу из двух столбцов и трёх строк. По сути она равнозначна запросу:
Более типично использование VALUES в составе большей команды SQL. Чаще всего она применяется в INSERT :
В контексте INSERT список VALUES может содержать слово DEFAULT , указывающее, что в данном месте вместо некоторого значения должно использоваться значение столбца по умолчанию:
VALUES также может применяться там, где можно написать вложенный SELECT , например в предложении FROM :
Заметьте, что когда VALUES используется в предложении FROM , предложение AS становится обязательным, так же, как и для SELECT . При этом не требуется указывать в AS имена всех столбцов, но это рекомендуется делать. (По умолчанию Postgres Pro даёт столбцам VALUES имена column1 , column2 и т. д., но в других СУБД имена могут быть другими.)
Когда VALUES используется в команде INSERT , значения автоматически приводятся к типу данных соответствующего целевого столбца. Когда оно используется в других контекстах, может потребоваться указать нужный тип данных. Если все записи представлены строковыми константами в кавычках, достаточно привести к нужному типу значения в первой строке, чтобы задать тип для всех:
Подсказка
Для простых проверок на включение IN лучше полагаться на форму IN со списком скаляров, чем записывать запрос VALUES , как показано выше. Список скаляров проще записать и обрабатывается он зачастую более эффективно.
Совместимость
VALUES соответствует стандарту SQL. Указания LIMIT и OFFSET являются расширениями Postgres Pro ; см. также SELECT .
Что такое values в sql
VALUES is a DML statement introduced in MySQL 8.0.19 which returns a set of one or more rows as a table. In other words, it is a table value constructor which also functions as a standalone SQL statement.
The VALUES statement consists of the VALUES keyword followed by a list of one or more row constructors, separated by commas. A row constructor consists of the ROW() row constructor clause with a value list of one or more scalar values enclosed in the parentheses. A value can be a literal of any MySQL data type or an expression that resolves to a scalar value.
ROW() cannot be empty (but each of the supplied scalar values can be NULL ). Each ROW() in the same VALUES statement must have the same number of values in its value list.
The DEFAULT keyword is not supported by VALUES and causes a syntax error, except when it is used to supply values in an INSERT statement.
The output of VALUES is a table:
The columns of the table output from VALUES have the implicitly named columns column_0 , column_1 , column_2 , and so on, always beginning with 0 . This fact can be used to order the rows by column using an optional ORDER BY clause in the same way that this clause works with a SELECT statement, as shown here:
In MySQL 8.0.21 and later, the VALUES statement also supports a LIMIT clause for limiting the number of rows in the output. (Previously, LIMIT was allowed but did nothing.)
The VALUES statement is permissive regarding data types of column values; you can mix types within the same column, as shown here:
VALUES with one or more instances of ROW() acts as a table value constructor; although it can be used to supply values in an INSERT or REPLACE statement, do not confuse it with the VALUES keyword that is also used for this purpose. You should also not confuse it with the VALUES() function that refers to column values in INSERT . ON DUPLICATE KEY UPDATE .
You should also bear in mind that ROW() is a row value constructor (see Section 13.2.15.5, “Row Subqueries”), whereas VALUES ROW() is a table value constructor; the two cannot be used interchangeably.
VALUES can be used in many cases where you could employ SELECT , including those listed here:
With UNION , as shown here:
You can union together constructed tables having more than one row, like this:
You can also (and it is usually preferable to) omit UNION altogether in such cases and use a single VALUES statement, like this:
VALUES can also be used in unions with SELECT statements, TABLE statements, or both.
The constructed tables in the UNION must contain the same number of columns, just as if you were using SELECT . See Section 13.2.18, “UNION Clause”, for further examples.
In MySQL 8.0.31 and later, you can use EXCEPT and INTERSECT with VALUES in much the same way as UNION , as shown here:
In joins. See Section 13.2.13.2, “JOIN Clause”, for more information and examples.
In place of VALUES() in an INSERT or REPLACE statement, in which case its semantics differ slightly from what is described here. See Section 13.2.7, “INSERT Statement”, for details.
In place of the source table in CREATE TABLE . SELECT and CREATE VIEW . SELECT . See the descriptions of these statements for more information and examples.