Как добавить данные в таблицу postgresql
INSERT — добавить строки в таблицу
Синтаксис
Описание
INSERT добавляет строки в таблицу. Эта команда может добавить одну или несколько строк, сформированных выражениями значений, либо ноль или более строк, выданных дополнительным запросом.
Имена целевых столбцов могут перечисляться в любом порядке. Если список с именами столбцов отсутствует, по умолчанию целевыми столбцами становятся все столбцы заданной таблицы; либо первые N из них, если только N столбцов поступает от предложения VALUES или запроса . Значения, получаемые от предложения VALUES или запроса , связываются с явно или неявно определённым списком столбцов слева направо.
Все столбцы, не представленные в явном или неявном списке столбцов, получат значения по умолчанию, если для них заданы эти значения, либо NULL в противном случае.
Если выражение для любого столбца выдаёт другой тип данных, система попытается автоматически привести его к нужному.
Операция INSERT с таблицами без уникальных индексов не блокируется параллельно выполняемыми операциями. В таблицах с уникальными индексами эта операция может блокироваться, если в параллельных сеансах выполняются действия, которые блокируют или изменяют строки, совпадающие с вставляемыми значениями в уникальном индексе; подробнее см. Раздел 64.5. Предложение ON CONFLICT позволяет задать действие, заменяющее возникновение ошибки при нарушении ограничения уникальности или ограничения-исключения. (См. описание Предложение ON CONFLICT ниже.)
С необязательным предложением RETURNING команда INSERT вычислит и возвратит значения для каждой фактически добавленной строки (или изменённой, если применялось предложение ON CONFLICT DO UPDATE ). В основном это полезно для получения значений, присвоенных по умолчанию, например, последовательного номера записи. Однако в этом предложении можно задать любое выражение со столбцами таблицы. Список RETURNING имеет тот же синтаксис, что и список результатов SELECT . В результате будут возвращены те строки, которые были успешно вставлены или изменены. Например, если строка была заблокирована, но не изменена, из-за того, что условие в предложении ON CONFLICT DO UPDATE . WHERE не удовлетворено, эта строка возвращена не будет.
Чтобы добавлять строки в таблицу, необходимо иметь право INSERT для неё. Если присутствует предложение ON CONFLICT DO UPDATE , также требуется иметь право UPDATE для этой таблицы.
Если указывается список столбцов, достаточно иметь право INSERT только для перечисленных столбцов. Аналогично, с предложением ON CONFLICT DO UPDATE достаточно иметь право UPDATE только для столбцов, которые будут изменены. Однако предложение ON CONFLICT DO UPDATE также требует наличия права SELECT для всех столбцов, значения которых считываются в выражениях ON CONFLICT DO UPDATE или в условии .
Для применения предложения RETURNING требуется право SELECT для всех столбцов, перечисленных в RETURNING . Если для добавления строк применяется запрос , для всех таблиц или столбцов, задействованных в этом запросе, разумеется, необходимо иметь право SELECT .
Параметры
Добавление
В этом разделе рассматриваются параметры, применяемые только при добавлении новых строк. Параметры, применяемые исключительно с предложением ON CONFLICT , описываются отдельно.
Предложение WITH позволяет задать один или несколько подзапросов, на которые затем можно ссылаться по имени в запросе INSERT . Подробнее об этом см. Раздел 7.8 и SELECT .
Заданный запрос (оператор SELECT ) также может содержать предложение WITH . В этом случае в запросе можно обращаться к обоим запросам_WITH , но второй будет иметь приоритет, так как он вложен ближе. имя_таблицы
Имя существующей таблицы (возможно, дополненное схемой). псевдоним
Альтернативное имя, заменяющее имя_таблицы . Когда указывается этот псевдоним, он полностью скрывает реальное имя таблицы. Это особенно полезно, когда в предложении ON CONFLICT DO UPDATE фигурирует таблица с именем excluded , так как без определения псевдонима это имя будет отдано специальной таблице, представляющей строку, предназначенную для добавления. имя_столбца
Имя столбца в таблице имя_таблицы . Это имя столбца при необходимости может быть дополнено именем вложенного поля или индексом в массиве. (Когда данные вставляются только в некоторые поля столбца составного типа, в другие поля записывается NULL.) Обращаясь к столбцу в предложении ON CONFLICT DO UPDATE , включать имя таблицы в ссылку на целевой столбец не нужно. Например, запись INSERT INTO table_name . ON CONFLICT DO UPDATE SET table_name.col = 1 некорректна (это согласуется с общим поведением команды UPDATE ). OVERRIDING SYSTEM VALUE
Если указывается это предложение, то значения, предоставляемые для столбцов идентификации, переопределяют значения, выдаваемые последовательностью по умолчанию.
Для столбца идентификации, определённого со свойством GENERATED ALWAYS , считается ошибкой присваивание явного значения (кроме DEFAULT) без указания OVERRIDING SYSTEM VALUE или OVERRIDING USER VALUE . (Для столбца идентификации, определённого со свойством GENERATED BY DEFAULT , указание OVERRIDING SYSTEM VALUE соответствует обычному поведению и ни на что не влияет, но PostgreSQL допускает его как дополнение.) OVERRIDING USER VALUE
Если указывается это предложение, то значения, предоставляемые для столбцов идентификации, игнорируются и вместо них применяются значения, выдаваемые последовательностью по умолчанию.
Это предложение полезно, например, при копировании значений между таблицами. Команда INSERT INTO tbl2 OVERRIDING USER VALUE SELECT * FROM tbl1 скопирует из tbl1 все столбцы, кроме столбцов идентификации в tbl2 , а значения столбцов идентификации в tbl2 будут сгенерированы последовательностями в tbl2 . DEFAULT VALUES
Все столбцы получат значения по умолчанию, как в случая явного указания DEFAULT для каждого столбца. (Предложение OVERRIDING в этой форме не допускается.) выражение
Выражение или значение, которое будет присвоено соответствующему столбцу. DEFAULT
Соответствующий столбец получит значение по умолчанию. Столбец идентификации получит новое значение, выданное связанной последовательностью. Для генерируемого столбца это указание допускается, но не меняет обычное поведение, то есть значение столбца вычисляется генерирующим выражением. запрос
Запрос (оператор SELECT ), который выдаст строки для добавления в таблицу. Его синтаксис описан в справке оператора SELECT . выражение_результата
Выражение, которое будет вычисляться и возвращаться командой INSERT после добавления или изменения каждой строки. В этом выражении можно использовать имена любых столбцов таблицы имя_таблицы . Чтобы получить все столбцы, достаточно написать * . имя_результата
Имя, назначаемое возвращаемому столбцу.
Предложение ON CONFLICT
Необязательное предложение ON CONFLICT задаёт действие, заменяющее возникновение ошибки при нарушении ограничения уникальности или ограничения-исключения. Для каждой отдельной строки, предложенной для добавления, добавление либо выполняется успешно, либо, если нарушается решающее ограничение или индекс, задаваемые как объект_конфликта , выполняется альтернативное действие_конфликта . Вариант ON CONFLICT DO NOTHING в качестве альтернативного действия просто отменяет добавление строки. Вариант ON CONFLICT DO UPDATE изменяет существующую строку, вызвавшую конфликт со строкой, предложенной для добавления.
Задаваемый объект_конфликта может выбирать уникальный индекс . Определение объекта, позволяющее выбрать индекс, включает один или несколько столбцов (их определяет имя_столбца_индекса ) и/или выражение_индекса и необязательный предикат_индекса . Все уникальные индексы в таблице имя_таблицы , которые, без учёта порядка столбцов, содержат в точности столбцы/выражения, определяющие объект_конфликта , выбираются как решающие индексы. Если указывается предикат_индекса , он должен, в качестве дополнительного требования выбора, удовлетворять индексам. Заметьте, что это означает, что не частичный уникальный индекс (уникальный индекс без предиката) будет выбран (и будет использоваться в ON CONFLICT ), если такой индекс удовлетворяет всем остальным критериям. Если попытка выбрать индекс оказывается неудачной, выдаётся ошибка.
ON CONFLICT DO UPDATE гарантирует атомарный результат команды INSERT или UPDATE ; при отсутствии внешних ошибок гарантируется один из двух этих исходов, даже при большой параллельной активности. Эта операция также известна как UPSERT — « UPDATE или INSERT » .
Определяет, для какого именно конфликта в ON CONFLICT будет предпринято альтернативное действие, устанавливая решающие индексы. Это указание позволяет осуществить выбор уникального индекса или явно задаёт имя ограничения. Для ON CONFLICT DO NOTHING объект_конфликта может не указываться; в этом случае игнорироваться будут все конфликты с любыми ограничениями (и уникальными индексами). Для ON CONFLICT DO UPDATE объект_конфликта должен указываться. действие_при_конфликте
Параметр действие_при_конфликте задаёт альтернативное действие в случае конфликта. Это может быть либо DO NOTHING (не делать ничего), либо предложение DO UPDATE (произвести изменение), в котором указываются точные детали операции UPDATE , выполняемой в случае конфликта. Предложения SET и WHERE в ON CONFLICT DO UPDATE могут обращаться к существующей строке по имени таблицы (или псевдониму) или к строке, предлагаемой для добавления, используя специальную таблицу excluded . Для чтения столбцов excluded необходимо иметь право SELECT для соответствующих столбцов в целевой таблице.
Заметьте, что эффект действий всех триггеров уровня строк BEFORE INSERT отражается в значениях excluded , так как в результате этих действий строка может быть исключена из множества добавляемых. имя_столбца_индекса
Имя столбца в таблице имя_таблицы . Используется для выбора решающих индексов. Задаётся в формате CREATE INDEX . Чтобы запрос выполнился, для столбца имя_столбца_индекса требуется право SELECT . выражение_индекса
Подобно указанию имя_столбца_индекса , но применяется для выбора индекса по выражениям со столбцами таблицы имя_таблицы , фигурирующим в определениях индексов (не по простым столбцам). Задаётся в формате CREATE INDEX . Для всех столбцов, к которым обращается выражение_индекса , необходимо иметь право SELECT . правило_сортировки
Когда задаётся, устанавливает, что соответствующие имя_столбца_индекса или выражение_индекса должны использовать определённый порядок сортировки, чтобы этот индекс мог быть выбран. Обычно это указание опускается, так как от правил сортировки чаще всего не зависит, произойдёт ли нарушение ограничений или нет. Задаётся в формате CREATE INDEX . класс_операторов
Когда задаётся, устанавливает, что соответствующие имя_столбца_индекса или выражение_индекса должны использовать определённый класс, чтобы индекс мог быть выбран. Обычно это указание опускается, потому что семантика равенства часто всё равно одна и та же в разных классах операторов типа, или потому что достаточно рассчитывать на то, что заданные уникальные индексы имеют адекватное определение равенства. Задаётся в формате CREATE INDEX . предикат_индекса
Используется для выбора частичных уникальных индексов. Выбраны могут быть любые индексы, удовлетворяющие предикату (при этом они могут не быть собственно частичными индексами). Задаётся в формате CREATE INDEX . Для всех столбцов, задействованных в предикате_индекса , требуется право SELECT . имя_ограничения
Явно задаёт решающее ограничение по имени, что заменяет неявный выбор ограничения или индекса. условие
Выражение, выдающее значение типа boolean . Изменены будут только те строки, для которых это выражение выдаст true , хотя при выборе действия ON CONFLICT DO UPDATE заблокируются все строки. Заметьте, что условие вычисляется в конце, после того как конфликт был признан претендующим на выполнение изменения.
Заметьте, что ограничения-исключения не могут быть решающими в ON CONFLICT DO UPDATE . Во всех случаях в качестве решающих поддерживаются только неоткладываемые ( NOT DEFERRABLE ) ограничения и уникальные индексы.
Команда INSERT с предложением ON CONFLICT DO UPDATE является « детерминированной » . Это означает, что этой команде не разрешено воздействовать на любую существующую строку больше одного раза; в случае такой ситуации возникнет ошибка нарушения мощности множества. Строки, предлагаемые для добавления, не должны дублироваться с точки зрения атрибутов, ограничиваемых решающим индексом или ограничением.
Заметьте, что в настоящий момент не поддерживается ситуация, когда конструкция ON CONFLICT DO UPDATE команды INSERT , применяемой к секционированной таблице, изменяет ключ разбиения в конфликтующей строке так, что эта строка должна быть перенесена в новую секцию.
Подсказка
Часто предпочтительнее использовать неявный выбор уникального индекса вместо непосредственного указания ограничения в виде ON CONFLICT ON CONSTRAINT имя_ограничения . Выбор продолжит корректно работать, когда нижележащий индекс будет заменён другим более или менее равнозначным индексом методом наложения, например, с использованием CREATE UNIQUE INDEX . CONCURRENTLY и последующим удалением заменяемого индекса.
Выводимая информация
В случае успешного завершения INSERT возвращает метку команды в виде
Если команда INSERT содержит предложение RETURNING , её результат будет похож на результат оператора SELECT (с теми же столбцами и значениями, что содержатся в списке RETURNING ), полученный для строк, добавленных или изменённых этой командой.
Замечания
Если целевая таблица является секционированной, каждая строка перенаправляется в соответствующую секцию и вставляется в неё. Если целевая таблица является секцией и какая-либо из входных строк нарушает ограничение этой секции, происходит ошибка.
Вы также можете использовать команду MERGE , так как она позволяет объединить команды INSERT , UPDATE и DELETE в одном операторе. См. MERGE .
Примеры
Добавление одной строки в таблицу films :
В этом примере столбец len опускается и, таким образом, получает значение по умолчанию:
В этом примере для столбца с датой задаётся указание DEFAULT , а не явное значение:
Добавление строки, полностью состоящей из значений по умолчанию:
Добавление нескольких строк с использованием многострочного синтаксиса VALUES :
В этом примере в таблицу films вставляются некоторые строки из таблицы tmp_films , имеющей ту же структуру столбцов, что и films :
Этот пример демонстрирует добавление данных в столбцы с типом массива:
Добавление одной строки в таблицу distributors и получение последовательного номера, сгенерированного благодаря указанию DEFAULT :
Увеличение счётчика продаж для продавца, занимающегося компанией Acme Corporation, и сохранение всей изменённой строки вместе с текущим временем в таблице журнала:
Добавить дистрибьюторов или изменить существующие данные должным образом. Предполагается, что в таблице определён уникальный индекс, ограничивающий значения в столбце did . Заметьте, что для обращения к значениям, изначально предлагаемым для добавления, используется специальная таблица excluded :
Добавить дистрибьютора или не делать ничего для строк, предложенных для добавления, если уже есть существующая исключающая строка (строка, содержащая конфликтующие значения в столбце или столбцах после срабатывания триггеров перед добавлением строки). В данном примере предполагается, что определён уникальный индекс, ограничивающий значения в столбце did :
Добавить дистрибьюторов или изменить существующие данные должным образом. В данном примере предполагается, что в таблице определён уникальный индекс, ограничивающий значения в столбце did . Предложение WHERE позволяет ограничить набор фактически изменяемых строк (однако любая существующая строка, не подлежащая изменению, всё же будет заблокирована):
Добавить дистрибьютора, если возможно; в противном случае не делать ничего ( DO NOTHING ). В данном примере предполагается, что в таблице определён уникальный индекс, ограничивающий значения в столбце did по подмножеству строк, в котором логический столбец is_active содержит true :
Совместимость
INSERT соответствует стандарту SQL, но предложение RETURNING относится к расширениям PostgreSQL , как и возможность применять WITH с INSERT и возможность задавать альтернативное действие с ON CONFLICT . Кроме того, ситуация, когда список столбцов опущен, но не все столбцы получают значения из предложения VALUES или запроса , стандартом не допускается. Если вы предпочитаете конструкции ON CONFLICT оператор, более соответствующий стандарту SQL, см. MERGE .
В стандарте SQL говорится, что предложение OVERRIDING SYSTEM VALUE может присутствовать, только если существует столбец идентификации, для которого всегда генерируется значение. PostgreSQL допускает это предложение в любом случае и игнорирует его в случае неприменимости.
Возможные ограничения предложения запрос описаны в справке SELECT .
Операции с данными
Для добавления данных применяется команда INSERT , которая имеет следующий формальный синтаксис:
После INSERT INTO идет имя таблицы, затем в скобках указываются все столбцы через запятую, в которые надо добавлять данные. И в конце после слова VALUES в скобках перечисляются добавляемые значения.
Допустим, у нас в базе данных есть следующая талица:
Добавим в нее одну строку с помощью команды INSERT:
После удачного выполнения в pgAdmin в поле сообщений должно появиться сообщение «INSERT 0 1»:
Стоит учитывать, что значения для столбцов в скобках после ключевого слова VALUES передаются по порядку их объявления. Например, в выражении CREATE TABLE выше можно увидеть, что первым столбцом идет Id, поэтому этому столбцу передаетсячисло 1. Второй столбец называется ProductName, поэтому второе значение — строка «Galaxy S9» будет передано именно этому столбцу и так далее. То есть значения передаются столбцам следующим образом:
ProductName: ‘Galaxy S9’
Также при вводе значений можно указать непосредственные столбцы, в которые будут добавляться значения:
Здесь значение указывается только для трех столбцов. Причем теперь значения передаются в порядке следования столбцов:
ProductName: ‘iPhone X’
Для столбца Id значение будет генерироваться автоматически базой данных, так как он представляет тип Serial. То есть к значению из последней строки будет добавляться единица.
Для остальных столбцов будет добавляться значение по умолчанию, если задан атрибут DEFAULT (например, для столбца ProductCount), значение NULL. При этом неуказанные столбцы (за исключением тех, которые имеют тип Serial) должны допускать значение NULL или иметь атрибут DEFAULT.
Если конкретные столбцы не указываются, как в первом примере, тогда мы должны передать значения для всех столбцов в таблице.
Также мы можем добавить сразу несколько строк:
В данном случае в таблицу будут добавлены три строки.
Возвращение значений
Если мы добавляем значения только для части столбцов, то мы можем не знать, какие значения будут у других столбцов. Например, какое значени получит столбец Id у товара. С помощью оператора RETURNING мы можем получить это значение:
Как добавить данные в таблицу postgresql
INSERT — create new rows in a table
Synopsis
Description
INSERT inserts new rows into a table. One can insert one or more rows specified by value expressions, or zero or more rows resulting from a query.
The target column names can be listed in any order. If no list of column names is given at all, the default is all the columns of the table in their declared order; or the first N column names, if there are only N columns supplied by the VALUES clause or query . The values supplied by the VALUES clause or query are associated with the explicit or implicit column list left-to-right.
Each column not present in the explicit or implicit column list will be filled with a default value, either its declared default value or null if there is none.
If the expression for any column is not of the correct data type, automatic type conversion will be attempted.
INSERT into tables that lack unique indexes will not be blocked by concurrent activity. Tables with unique indexes might block if concurrent sessions perform actions that lock or modify rows matching the unique index values being inserted; the details are covered in Section 64.5. ON CONFLICT can be used to specify an alternative action to raising a unique constraint or exclusion constraint violation error. (See ON CONFLICT Clause below.)
The optional RETURNING clause causes INSERT to compute and return value(s) based on each row actually inserted (or updated, if an ON CONFLICT DO UPDATE clause was used). This is primarily useful for obtaining values that were supplied by defaults, such as a serial sequence number. However, any expression using the table’s columns is allowed. The syntax of the RETURNING list is identical to that of the output list of SELECT . Only rows that were successfully inserted or updated will be returned. For example, if a row was locked but not updated because an ON CONFLICT DO UPDATE . WHERE clause condition was not satisfied, the row will not be returned.
You must have INSERT privilege on a table in order to insert into it. If ON CONFLICT DO UPDATE is present, UPDATE privilege on the table is also required.
If a column list is specified, you only need INSERT privilege on the listed columns. Similarly, when ON CONFLICT DO UPDATE is specified, you only need UPDATE privilege on the column(s) that are listed to be updated. However, ON CONFLICT DO UPDATE also requires SELECT privilege on any column whose values are read in the ON CONFLICT DO UPDATE expressions or condition .
Use of the RETURNING clause requires SELECT privilege on all columns mentioned in RETURNING . If you use the query clause to insert rows from a query, you of course need to have SELECT privilege on any table or column used in the query.
Parameters
Inserting
This section covers parameters that may be used when only inserting new rows. Parameters exclusively used with the ON CONFLICT clause are described separately.
The WITH clause allows you to specify one or more subqueries that can be referenced by name in the INSERT query. See Section 7.8 and SELECT for details.
It is possible for the query ( SELECT statement) to also contain a WITH clause. In such a case both sets of with_query can be referenced within the query , but the second one takes precedence since it is more closely nested. table_name
The name (optionally schema-qualified) of an existing table. alias
A substitute name for table_name . When an alias is provided, it completely hides the actual name of the table. This is particularly useful when ON CONFLICT DO UPDATE targets a table named excluded , since that will otherwise be taken as the name of the special table representing the row proposed for insertion. column_name
The name of a column in the table named by table_name . The column name can be qualified with a subfield name or array subscript, if needed. (Inserting into only some fields of a composite column leaves the other fields null.) When referencing a column with ON CONFLICT DO UPDATE , do not include the table’s name in the specification of a target column. For example, INSERT INTO table_name . ON CONFLICT DO UPDATE SET table_name.col = 1 is invalid (this follows the general behavior for UPDATE ). OVERRIDING SYSTEM VALUE
If this clause is specified, then any values supplied for identity columns will override the default sequence-generated values.
For an identity column defined as GENERATED ALWAYS , it is an error to insert an explicit value (other than DEFAULT ) without specifying either OVERRIDING SYSTEM VALUE or OVERRIDING USER VALUE . (For an identity column defined as GENERATED BY DEFAULT , OVERRIDING SYSTEM VALUE is the normal behavior and specifying it does nothing, but PostgreSQL allows it as an extension.) OVERRIDING USER VALUE
If this clause is specified, then any values supplied for identity columns are ignored and the default sequence-generated values are applied.
This clause is useful for example when copying values between tables. Writing INSERT INTO tbl2 OVERRIDING USER VALUE SELECT * FROM tbl1 will copy from tbl1 all columns that are not identity columns in tbl2 while values for the identity columns in tbl2 will be generated by the sequences associated with tbl2 . DEFAULT VALUES
All columns will be filled with their default values, as if DEFAULT were explicitly specified for each column. (An OVERRIDING clause is not permitted in this form.) expression
An expression or value to assign to the corresponding column. DEFAULT
The corresponding column will be filled with its default value. An identity column will be filled with a new value generated by the associated sequence. For a generated column, specifying this is permitted but merely specifies the normal behavior of computing the column from its generation expression. query
A query ( SELECT statement) that supplies the rows to be inserted. Refer to the SELECT statement for a description of the syntax. output_expression
An expression to be computed and returned by the INSERT command after each row is inserted or updated. The expression can use any column names of the table named by table_name . Write * to return all columns of the inserted or updated row(s). output_name
A name to use for a returned column.
ON CONFLICT Clause
The optional ON CONFLICT clause specifies an alternative action to raising a unique violation or exclusion constraint violation error. For each individual row proposed for insertion, either the insertion proceeds, or, if an arbiter constraint or index specified by conflict_target is violated, the alternative conflict_action is taken. ON CONFLICT DO NOTHING simply avoids inserting a row as its alternative action. ON CONFLICT DO UPDATE updates the existing row that conflicts with the row proposed for insertion as its alternative action.
conflict_target can perform unique index inference . When performing inference, it consists of one or more index_column_name columns and/or index_expression expressions, and an optional index_predicate . All table_name unique indexes that, without regard to order, contain exactly the conflict_target -specified columns/expressions are inferred (chosen) as arbiter indexes. If an index_predicate is specified, it must, as a further requirement for inference, satisfy arbiter indexes. Note that this means a non-partial unique index (a unique index without a predicate) will be inferred (and thus used by ON CONFLICT ) if such an index satisfying every other criteria is available. If an attempt at inference is unsuccessful, an error is raised.
ON CONFLICT DO UPDATE guarantees an atomic INSERT or UPDATE outcome; provided there is no independent error, one of those two outcomes is guaranteed, even under high concurrency. This is also known as UPSERT — “ UPDATE or INSERT ” .
Specifies which conflicts ON CONFLICT takes the alternative action on by choosing arbiter indexes. Either performs unique index inference , or names a constraint explicitly. For ON CONFLICT DO NOTHING , it is optional to specify a conflict_target ; when omitted, conflicts with all usable constraints (and unique indexes) are handled. For ON CONFLICT DO UPDATE , a conflict_target must be provided. conflict_action
conflict_action specifies an alternative ON CONFLICT action. It can be either DO NOTHING , or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict. The SET and WHERE clauses in ON CONFLICT DO UPDATE have access to the existing row using the table’s name (or an alias), and to the row proposed for insertion using the special excluded table. SELECT privilege is required on any column in the target table where corresponding excluded columns are read.
Note that the effects of all per-row BEFORE INSERT triggers are reflected in excluded values, since those effects may have contributed to the row being excluded from insertion. index_column_name
The name of a table_name column. Used to infer arbiter indexes. Follows CREATE INDEX format. SELECT privilege on index_column_name is required. index_expression
Similar to index_column_name , but used to infer expressions on table_name columns appearing within index definitions (not simple columns). Follows CREATE INDEX format. SELECT privilege on any column appearing within index_expression is required. collation
When specified, mandates that corresponding index_column_name or index_expression use a particular collation in order to be matched during inference. Typically this is omitted, as collations usually do not affect whether or not a constraint violation occurs. Follows CREATE INDEX format. opclass
When specified, mandates that corresponding index_column_name or index_expression use particular operator class in order to be matched during inference. Typically this is omitted, as the equality semantics are often equivalent across a type’s operator classes anyway, or because it’s sufficient to trust that the defined unique indexes have the pertinent definition of equality. Follows CREATE INDEX format. index_predicate
Used to allow inference of partial unique indexes. Any indexes that satisfy the predicate (which need not actually be partial indexes) can be inferred. Follows CREATE INDEX format. SELECT privilege on any column appearing within index_predicate is required. constraint_name
Explicitly specifies an arbiter constraint by name, rather than inferring a constraint or index. condition
An expression that returns a value of type boolean . Only rows for which this expression returns true will be updated, although all rows will be locked when the ON CONFLICT DO UPDATE action is taken. Note that condition is evaluated last, after a conflict has been identified as a candidate to update.
Note that exclusion constraints are not supported as arbiters with ON CONFLICT DO UPDATE . In all cases, only NOT DEFERRABLE constraints and unique indexes are supported as arbiters.
INSERT with an ON CONFLICT DO UPDATE clause is a “ deterministic ” statement. This means that the command will not be allowed to affect any single existing row more than once; a cardinality violation error will be raised when this situation arises. Rows proposed for insertion should not duplicate each other in terms of attributes constrained by an arbiter index or constraint.
Note that it is currently not supported for the ON CONFLICT DO UPDATE clause of an INSERT applied to a partitioned table to update the partition key of a conflicting row such that it requires the row be moved to a new partition.
It is often preferable to use unique index inference rather than naming a constraint directly using ON CONFLICT ON CONSTRAINT constraint_name . Inference will continue to work correctly when the underlying index is replaced by another more or less equivalent index in an overlapping way, for example when using CREATE UNIQUE INDEX . CONCURRENTLY before dropping the index being replaced.
Outputs
On successful completion, an INSERT command returns a command tag of the form
If the INSERT command contains a RETURNING clause, the result will be similar to that of a SELECT statement containing the columns and values defined in the RETURNING list, computed over the row(s) inserted or updated by the command.
Notes
If the specified table is a partitioned table, each row is routed to the appropriate partition and inserted into it. If the specified table is a partition, an error will occur if one of the input rows violates the partition constraint.
You may also wish to consider using MERGE , since that allows mixing INSERT , UPDATE , and DELETE within a single statement. See MERGE .
Examples
Insert a single row into table films :
In this example, the len column is omitted and therefore it will have the default value:
This example uses the DEFAULT clause for the date columns rather than specifying a value:
To insert a row consisting entirely of default values:
To insert multiple rows using the multirow VALUES syntax:
This example inserts some rows into table films from a table tmp_films with the same column layout as films :
This example inserts into array columns:
Insert a single row into table distributors , returning the sequence number generated by the DEFAULT clause:
Increment the sales count of the salesperson who manages the account for Acme Corporation, and record the whole updated row along with current time in a log table:
Insert or update new distributors as appropriate. Assumes a unique index has been defined that constrains values appearing in the did column. Note that the special excluded table is used to reference values originally proposed for insertion:
Insert a distributor, or do nothing for rows proposed for insertion when an existing, excluded row (a row with a matching constrained column or columns after before row insert triggers fire) exists. Example assumes a unique index has been defined that constrains values appearing in the did column:
Insert or update new distributors as appropriate. Example assumes a unique index has been defined that constrains values appearing in the did column. WHERE clause is used to limit the rows actually updated (any existing row not updated will still be locked, though):
Insert new distributor if possible; otherwise DO NOTHING . Example assumes a unique index has been defined that constrains values appearing in the did column on a subset of rows where the is_active Boolean column evaluates to true :
Compatibility
INSERT conforms to the SQL standard, except that the RETURNING clause is a PostgreSQL extension, as is the ability to use WITH with INSERT , and the ability to specify an alternative action with ON CONFLICT . Also, the case in which a column name list is omitted, but not all the columns are filled from the VALUES clause or query , is disallowed by the standard. If you prefer a more SQL standard conforming statement than ON CONFLICT , see MERGE .
The SQL standard specifies that OVERRIDING SYSTEM VALUE can only be specified if an identity column that is generated always exists. PostgreSQL allows the clause in any case and ignores it if it is not applicable.
Possible limitations of the query clause are documented under SELECT .
Как добавить данные в таблицу postgresql
INSERT inserts new rows into a table. One can insert one or more rows specified by value expressions, or zero or more rows resulting from a query.
The target column names can be listed in any order. If no list of column names is given at all, the default is all the columns of the table in their declared order; or the first N column names, if there are only N columns supplied by the VALUES clause or query . The values supplied by the VALUES clause or query are associated with the explicit or implicit column list left-to-right.
Each column not present in the explicit or implicit column list will be filled with a default value, either its declared default value or null if there is none.
If the expression for any column is not of the correct data type, automatic type conversion will be attempted.
INSERT into tables that lack unique indexes will not be blocked by concurrent activity. Tables with unique indexes might block if concurrent sessions perform actions that lock or modify rows matching the unique index values being inserted; the details are covered in Section 64.5. ON CONFLICT can be used to specify an alternative action to raising a unique constraint or exclusion constraint violation error. (See ON CONFLICT Clause below.)
The optional RETURNING clause causes INSERT to compute and return value(s) based on each row actually inserted (or updated, if an ON CONFLICT DO UPDATE clause was used). This is primarily useful for obtaining values that were supplied by defaults, such as a serial sequence number. However, any expression using the table’s columns is allowed. The syntax of the RETURNING list is identical to that of the output list of SELECT . Only rows that were successfully inserted or updated will be returned. For example, if a row was locked but not updated because an ON CONFLICT DO UPDATE . WHERE clause condition was not satisfied, the row will not be returned.
You must have INSERT privilege on a table in order to insert into it. If ON CONFLICT DO UPDATE is present, UPDATE privilege on the table is also required.
If a column list is specified, you only need INSERT privilege on the listed columns. Similarly, when ON CONFLICT DO UPDATE is specified, you only need UPDATE privilege on the column(s) that are listed to be updated. However, ON CONFLICT DO UPDATE also requires SELECT privilege on any column whose values are read in the ON CONFLICT DO UPDATE expressions or condition .
Use of the RETURNING clause requires SELECT privilege on all columns mentioned in RETURNING . If you use the query clause to insert rows from a query, you of course need to have SELECT privilege on any table or column used in the query.
Parameters
Inserting
This section covers parameters that may be used when only inserting new rows. Parameters exclusively used with the ON CONFLICT clause are described separately.
The WITH clause allows you to specify one or more subqueries that can be referenced by name in the INSERT query. See Section 7.8 and SELECT for details.
It is possible for the query ( SELECT statement) to also contain a WITH clause. In such a case both sets of with_query can be referenced within the query , but the second one takes precedence since it is more closely nested.
The name (optionally schema-qualified) of an existing table.
A substitute name for table_name . When an alias is provided, it completely hides the actual name of the table. This is particularly useful when ON CONFLICT DO UPDATE targets a table named excluded , since that will otherwise be taken as the name of the special table representing the row proposed for insertion.
The name of a column in the table named by table_name . The column name can be qualified with a subfield name or array subscript, if needed. (Inserting into only some fields of a composite column leaves the other fields null.) When referencing a column with ON CONFLICT DO UPDATE , do not include the table’s name in the specification of a target column. For example, INSERT INTO table_name . ON CONFLICT DO UPDATE SET table_name.col = 1 is invalid (this follows the general behavior for UPDATE ).
OVERRIDING SYSTEM VALUE
If this clause is specified, then any values supplied for identity columns will override the default sequence-generated values.
For an identity column defined as GENERATED ALWAYS , it is an error to insert an explicit value (other than DEFAULT ) without specifying either OVERRIDING SYSTEM VALUE or OVERRIDING USER VALUE . (For an identity column defined as GENERATED BY DEFAULT , OVERRIDING SYSTEM VALUE is the normal behavior and specifying it does nothing, but PostgreSQL allows it as an extension.)
OVERRIDING USER VALUE
If this clause is specified, then any values supplied for identity columns are ignored and the default sequence-generated values are applied.
This clause is useful for example when copying values between tables. Writing INSERT INTO tbl2 OVERRIDING USER VALUE SELECT * FROM tbl1 will copy from tbl1 all columns that are not identity columns in tbl2 while values for the identity columns in tbl2 will be generated by the sequences associated with tbl2 .
All columns will be filled with their default values, as if DEFAULT were explicitly specified for each column. (An OVERRIDING clause is not permitted in this form.)
An expression or value to assign to the corresponding column.
The corresponding column will be filled with its default value. An identity column will be filled with a new value generated by the associated sequence. For a generated column, specifying this is permitted but merely specifies the normal behavior of computing the column from its generation expression.
A query ( SELECT statement) that supplies the rows to be inserted. Refer to the SELECT statement for a description of the syntax.
An expression to be computed and returned by the INSERT command after each row is inserted or updated. The expression can use any column names of the table named by table_name . Write * to return all columns of the inserted or updated row(s).
A name to use for a returned column.
ON CONFLICT Clause
The optional ON CONFLICT clause specifies an alternative action to raising a unique violation or exclusion constraint violation error. For each individual row proposed for insertion, either the insertion proceeds, or, if an arbiter constraint or index specified by conflict_target is violated, the alternative conflict_action is taken. ON CONFLICT DO NOTHING simply avoids inserting a row as its alternative action. ON CONFLICT DO UPDATE updates the existing row that conflicts with the row proposed for insertion as its alternative action.
conflict_target can perform unique index inference . When performing inference, it consists of one or more index_column_name columns and/or index_expression expressions, and an optional index_predicate . All table_name unique indexes that, without regard to order, contain exactly the conflict_target -specified columns/expressions are inferred (chosen) as arbiter indexes. If an index_predicate is specified, it must, as a further requirement for inference, satisfy arbiter indexes. Note that this means a non-partial unique index (a unique index without a predicate) will be inferred (and thus used by ON CONFLICT ) if such an index satisfying every other criteria is available. If an attempt at inference is unsuccessful, an error is raised.
ON CONFLICT DO UPDATE guarantees an atomic INSERT or UPDATE outcome; provided there is no independent error, one of those two outcomes is guaranteed, even under high concurrency. This is also known as UPSERT — “ UPDATE or INSERT ” .
Specifies which conflicts ON CONFLICT takes the alternative action on by choosing arbiter indexes. Either performs unique index inference , or names a constraint explicitly. For ON CONFLICT DO NOTHING , it is optional to specify a conflict_target ; when omitted, conflicts with all usable constraints (and unique indexes) are handled. For ON CONFLICT DO UPDATE , a conflict_target must be provided.
conflict_action specifies an alternative ON CONFLICT action. It can be either DO NOTHING , or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict. The SET and WHERE clauses in ON CONFLICT DO UPDATE have access to the existing row using the table’s name (or an alias), and to the row proposed for insertion using the special excluded table. SELECT privilege is required on any column in the target table where corresponding excluded columns are read.
Note that the effects of all per-row BEFORE INSERT triggers are reflected in excluded values, since those effects may have contributed to the row being excluded from insertion.
The name of a table_name column. Used to infer arbiter indexes. Follows CREATE INDEX format. SELECT privilege on index_column_name is required.
Similar to index_column_name , but used to infer expressions on table_name columns appearing within index definitions (not simple columns). Follows CREATE INDEX format. SELECT privilege on any column appearing within index_expression is required.
When specified, mandates that corresponding index_column_name or index_expression use a particular collation in order to be matched during inference. Typically this is omitted, as collations usually do not affect whether or not a constraint violation occurs. Follows CREATE INDEX format.
When specified, mandates that corresponding index_column_name or index_expression use particular operator class in order to be matched during inference. Typically this is omitted, as the equality semantics are often equivalent across a type’s operator classes anyway, or because it’s sufficient to trust that the defined unique indexes have the pertinent definition of equality. Follows CREATE INDEX format.
Used to allow inference of partial unique indexes. Any indexes that satisfy the predicate (which need not actually be partial indexes) can be inferred. Follows CREATE INDEX format. SELECT privilege on any column appearing within index_predicate is required.
Explicitly specifies an arbiter constraint by name, rather than inferring a constraint or index.
An expression that returns a value of type boolean . Only rows for which this expression returns true will be updated, although all rows will be locked when the ON CONFLICT DO UPDATE action is taken. Note that condition is evaluated last, after a conflict has been identified as a candidate to update.
Note that exclusion constraints are not supported as arbiters with ON CONFLICT DO UPDATE . In all cases, only NOT DEFERRABLE constraints and unique indexes are supported as arbiters.
INSERT with an ON CONFLICT DO UPDATE clause is a “ deterministic ” statement. This means that the command will not be allowed to affect any single existing row more than once; a cardinality violation error will be raised when this situation arises. Rows proposed for insertion should not duplicate each other in terms of attributes constrained by an arbiter index or constraint.
Note that it is currently not supported for the ON CONFLICT DO UPDATE clause of an INSERT applied to a partitioned table to update the partition key of a conflicting row such that it requires the row be moved to a new partition.
It is often preferable to use unique index inference rather than naming a constraint directly using ON CONFLICT ON CONSTRAINT constraint_name . Inference will continue to work correctly when the underlying index is replaced by another more or less equivalent index in an overlapping way, for example when using CREATE UNIQUE INDEX . CONCURRENTLY before dropping the index being replaced.
Outputs
On successful completion, an INSERT command returns a command tag of the form
If the INSERT command contains a RETURNING clause, the result will be similar to that of a SELECT statement containing the columns and values defined in the RETURNING list, computed over the row(s) inserted or updated by the command.
Notes
If the specified table is a partitioned table, each row is routed to the appropriate partition and inserted into it. If the specified table is a partition, an error will occur if one of the input rows violates the partition constraint.
You may also wish to consider using MERGE , since that allows mixing INSERT , UPDATE , and DELETE within a single statement. See MERGE .
Examples
Insert a single row into table films :
In this example, the len column is omitted and therefore it will have the default value:
This example uses the DEFAULT clause for the date columns rather than specifying a value:
To insert a row consisting entirely of default values:
To insert multiple rows using the multirow VALUES syntax:
This example inserts some rows into table films from a table tmp_films with the same column layout as films :
This example inserts into array columns:
Insert a single row into table distributors , returning the sequence number generated by the DEFAULT clause:
Increment the sales count of the salesperson who manages the account for Acme Corporation, and record the whole updated row along with current time in a log table:
Insert or update new distributors as appropriate. Assumes a unique index has been defined that constrains values appearing in the did column. Note that the special excluded table is used to reference values originally proposed for insertion:
Insert a distributor, or do nothing for rows proposed for insertion when an existing, excluded row (a row with a matching constrained column or columns after before row insert triggers fire) exists. Example assumes a unique index has been defined that constrains values appearing in the did column:
Insert or update new distributors as appropriate. Example assumes a unique index has been defined that constrains values appearing in the did column. WHERE clause is used to limit the rows actually updated (any existing row not updated will still be locked, though):
Insert new distributor if possible; otherwise DO NOTHING . Example assumes a unique index has been defined that constrains values appearing in the did column on a subset of rows where the is_active Boolean column evaluates to true :
Compatibility
INSERT conforms to the SQL standard, except that the RETURNING clause is a PostgreSQL extension, as is the ability to use WITH with INSERT , and the ability to specify an alternative action with ON CONFLICT . Also, the case in which a column name list is omitted, but not all the columns are filled from the VALUES clause or query , is disallowed by the standard. If you prefer a more SQL standard conforming statement than ON CONFLICT , see MERGE .
The SQL standard specifies that OVERRIDING SYSTEM VALUE can only be specified if an identity column that is generated always exists. PostgreSQL allows the clause in any case and ignores it if it is not applicable.
Possible limitations of the query clause are documented under SELECT .
| Prev | Up | Next |
| IMPORT FOREIGN SCHEMA | Home | LISTEN |
Submit correction
If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please use this form to report a documentation issue.