INSERT(7)

πŸ“¦ version 13.23, in opensuse-leap 16.0

okay bestie, welcome to the INSERT(7) page from the PostgreSQL 13.23 Documentation β€” this one is literally all about creating new rows in a table, and we're gonna go through every detail. no cap. πŸ’…

πŸŽ€ NAME πŸŽ€

INSERT β€” create new rows in a table ✨

πŸ¦‹ SYNOPSIS πŸ¦‹

[ WITH [ RECURSIVE ] with_query [, ...] ]
INSERT INTO table_name [ AS alias ] [ ( column_name [, ...] ) ]
    [ OVERRIDING { SYSTEM | USER } VALUE ]
    { DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] ) [, ...] | query }
    [ ON CONFLICT [ conflict_target ] conflict_action ]
    [ RETURNING { * | output_expression [ [ AS ] output_name ] } [, ...] ]

where conflict_target can be one of:

    ( { index_column_name | ( index_expression ) } [ COLLATE collation ] [ opclass ] [, ...] ) [ WHERE index_predicate ]
    ON CONSTRAINT constraint_name

and conflict_action is one of:

    DO NOTHING
    DO UPDATE SET { column_name = { expression | DEFAULT } |
                    ( column_name [, ...] ) = [ ROW ] ( { expression | DEFAULT } [, ...] ) |
                    ( column_name [, ...] ) = ( sub-SELECT )
                  } [, ...]
              [ WHERE condition ]

πŸ’… DESCRIPTION πŸ’…

okay so INSERT inserts new rows into a table. you can insert one or more rows specified by value expressions, or zero or more rows that come from a query. it's giving β€œnew data, who dis” energy. 🫢

the target column names can be listed in any order. if you don't give a column-name list 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. periodt. ⭐

each column that's not present in the explicit or implicit column list gets filled with a default value β€” either its declared default value, or null if there isn't one. πŸŽ€

if the expression for any column is not the correct data type, automatic type conversion will be attempted. lowkey magical, but that's the rule. ✨

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 61.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. no crumbs left behind, bestie. πŸ“

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 ✨

okay so this whole section is about the parameters you use when you're only inserting new rows. the ones that are exclusively for the ON CONFLICT clause get their own section later, don't worry bestie 🫢

  • with_query β€” the WITH clause lets you name one or more subqueries and then reference them by name in the INSERT query. peep Section 7.8 and SELECT(7) for the deets ✨ also, it's totally possible for the query (the SELECT statement) to have its own WITH clause too β€” in that case both sets of with_query can be referenced inside the query, but the second one takes precedence since it's more closely nested. nested-ception πŸ’«
  • table_name β€” the name (optionally schema-qualified) of an existing table. that's the whole vibe.
  • alias β€” a substitute name for table_name. when you give one, it completely hides the actual name of the table (iconic, honestly). this is especially useful when ON CONFLICT DO UPDATE is targeting a table literally named excluded, because otherwise that name gets taken as the special table representing the row proposed for insertion 😭 naming collision behavior fr fr.
  • column_name β€” the name of a column in the table named by table_name. you can qualify the column name with a subfield name or array subscript if you need to. (quick psa: inserting into only some fields of a composite column leaves the other fields null, no cap.) and when you're 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 β€” specify this and any values you supply for identity columns will override the default sequence-generated values. for an identity column defined as GENERATED ALWAYS, it's 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. generous queen.)
  • OVERRIDING USER VALUE β€” specify this and any values supplied for identity columns get ignored, and the default sequence-generated values are applied instead. this 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. chef's kiss πŸŽ€
  • 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, noted πŸ“Œ)
  • expression β€” an expression or value to assign to the corresponding column.
  • DEFAULT β€” the corresponding column gets filled with its default value. an identity column gets filled with a new value generated by the associated sequence. for a generated column, specifying this is permitted but it merely specifies the normal behavior of computing the column from its generation expression. so like... it's a formality πŸ’…
  • query β€” a query (a SELECT statement) that supplies the rows to be inserted. SELECT(7) has the full syntax description.
  • 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 instead. 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. two paths, one destiny ✨

conflict_target can perform unique index inference. when it's doing inference, it consists of one or more index_column_name columns and/or index_expression expressions, plus an optional index_predicate. all table_name unique indexes that β€” without regard to order β€” contain exactly the conflict_target-specified columns/expressions get inferred (chosen) as arbiter indexes. if you specify an index_predicate, it must, as a further requirement for inference, satisfy arbiter indexes. quick heads up: 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's no independent error, one of those two outcomes is guaranteed, even under high concurrency. this is also known as UPSERT β€” "UPDATE or INSERT". main character behavior tbh πŸ‘‘

  • conflict_target β€” specifies which conflicts ON CONFLICT takes the alternative action on, by choosing arbiter indexes. it either performs unique index inference, or names a constraint explicitly. for ON CONFLICT DO NOTHING, specifying a conflict_target is optional β€” when it's 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 πŸ”

also 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. chain reaction vibes.

  • 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 the corresponding index_column_name or index_expression use a particular collation in order to be matched during inference. typically this is omitted, since collations usually don't affect whether or not a constraint violation occurs. follows CREATE INDEX format.
  • opclass β€” when specified, mandates that the corresponding index_column_name or index_expression use a particular operator class in order to be matched during inference. typically this is omitted too, since 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. that means the command won't 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 shouldn't duplicate each other in terms of attributes constrained by an arbiter index or constraint. one row, one glow-up, periodt πŸ’…

also note that it's 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. not today, bestie πŸ™…β€β™€οΈ

Tip πŸ’‘ it's 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. smart girl energy ✨
Warning ⚠️ while CREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY is running on a unique index, INSERT ... ON CONFLICT statements on the same table may unexpectedly fail with a unique violation. yeah. that's a thing. be aware 😭

✨ OUTPUTS ✨

on successful completion, an INSERT command returns a command tag of the form

INSERT oid count

count is the number of rows inserted or updated. oid is always 0 (it used to be the OID assigned to the inserted row if count was exactly one and the target table was declared WITH OIDS and 0 otherwise, but creating a table WITH OIDS is not supported anymore β€” rip to that era πŸͺ¦).

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. cute little receipt 🧾

🌸 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. know your place, row πŸ’–

✨ EXAMPLES ✨

Okay bestie, this is the part where it all comes together πŸ’… Let's insert some rows fr fr.

Say you wanna drop a single row into the films table β€” easy:

INSERT INTO films VALUES
    ('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes');

Now watch this trick πŸ‘€ In this next one the len column is just... not invited. It's omitted, which means it gets its default value:

INSERT INTO films (code, title, did, date_prod, kind)
    VALUES ('T_601', 'Yojimbo', 106, '1961-06-16', 'Drama');

Same energy, but now we're using the DEFAULT clause for the date columns instead of giving them an actual value πŸŽ€:

INSERT INTO films VALUES
    ('UA502', 'Bananas', 105, DEFAULT, 'Comedy', '82 minutes');
INSERT INTO films (code, title, did, date_prod, kind)
    VALUES ('T_601', 'Yojimbo', 106, DEFAULT, 'Drama');

Wanna insert a row that is literally nothing but defaults? Iconic. Main character energy:

INSERT INTO films DEFAULT VALUES;

Multirow VALUES syntax, aka the group chat way to insert πŸ‘―β€β™€οΈ:

INSERT INTO films (code, title, did, date_prod, kind) VALUES
    ('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
    ('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy');

This one pulls rows into films from a table called tmp_films that has the same column layout as films β€” copy-paste but make it SQL:

INSERT INTO films SELECT * FROM tmp_films WHERE date_prod < '2004-05-07';

Array columns?? We love her πŸ’– Check it, a whole noughts-and-crosses situation:

-- Create an empty 3x3 gameboard for noughts-and-crosses
INSERT INTO tictactoe (game, board[1:3][1:3])
    VALUES (1, '{{" "," "," "},{" "," "," "},{" "," "," "}}');
-- The subscripts in the above example aren't really needed
INSERT INTO tictactoe (game, board)
    VALUES (2, '{{X," "," "},{" ",O," "},{" ",X," "}}');
Ngl, the subscripts in that first one? Not really needed. The manpage said so, not me 😌

Now, insert one row into distributors and get back the sequence number that the DEFAULT clause cooked up β€” RETURNING is giving "and bring receipts" ✨:

INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets')
   RETURNING did;

Here's a whole situation: bump the sales count of whichever salesperson manages the account for Acme Corporation, and log the whole updated row plus the current time into a log table. CTE making it happen πŸ¦‹:

WITH upd AS (
  UPDATE employees SET sales_count = sales_count + 1 WHERE id =
    (SELECT sales_person FROM accounts WHERE name = 'Acme Corporation')
    RETURNING *
)
INSERT INTO employees_log SELECT *, current_timestamp FROM upd;

Insert-or-update new distributors as appropriate. This example 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 β€” that's the glow-up secret right there πŸ’…:

INSERT INTO distributors (did, dname)
    VALUES (5, 'Gizmo Transglobal'), (6, 'Associated Computing, Inc')
    ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname;

Or insert a distributor, or do nothing for rows proposed for insertion when an existing, excluded row exists β€” and to be clear, that's a row with a matching constrained column or columns after before row insert triggers fire. Example assumes a unique index has been defined that constrains values appearing in the did column:

INSERT INTO distributors (did, dname) VALUES (7, 'Redline GmbH')
    ON CONFLICT (did) DO NOTHING;

Insert or update, as appropriate. Example assumes a unique index has been defined that constrains values appearing in the did column. The WHERE clause is used to limit the rows actually updated β€” but heads up, any existing row that isn't updated will still be locked, though πŸ”’:

-- Don't update existing distributors based in a certain ZIP code
INSERT INTO distributors AS d (did, dname) VALUES (8, 'Anvil Distribution')
    ON CONFLICT (did) DO UPDATE
    SET dname = EXCLUDED.dname || ' (formerly ' || d.dname || ')'
    WHERE d.zipcode <> '21201';

-- Name a constraint directly in the statement (uses associated
-- index to arbitrate taking the DO NOTHING action)
INSERT INTO distributors (did, dname) VALUES (9, 'Antwerp Design')
    ON CONFLICT ON CONSTRAINT distributors_pkey DO NOTHING;

Last one πŸŽ€ Insert a 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:

-- This statement could infer a partial unique index on "did"
-- with a predicate of "WHERE is_active", but it could also
-- just use a regular unique constraint on "did"
INSERT INTO distributors (did, dname) VALUES (10, 'Conrad International')
    ON CONFLICT (did) WHERE is_active DO NOTHING;

🌈 COMPATIBILITY 🌈

INSERT conforms to the SQL standard β€” except the RETURNING clause is a PostgreSQL extension ✨ Same deal for the ability to use WITH with INSERT, and the ability to specify an alternative action with ON CONFLICT. Also, the case where a column name list is omitted but not all the columns are filled from the VALUES clause or query? The standard disallows that. Not us. We're built different πŸ’€

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 just ignores it if it's not applicable β€” no notes, no drama πŸ™ˆ

Possible limitations of the query clause are documented under SELECT(7) β€” go read that bestie, iykyk πŸ“–


okay that's the whole page, you made it 🫢 This little masterpiece comes from PostgreSQL 13.23, dated 2025, and it's literally called INSERT(7). Slay, go insert something πŸ’–βœ¨πŸŽ€

πŸ“¦ where this page comes from