INSERT

Synopsis

Use the INSERT statement to add one or more rows to the specified table.

Syntax

  1. insert ::= [ WITH [ RECURSIVE ] with_query [ , ... ] ] INSERT INTO
  2. table_name [ AS alias ] [ ( column_names ) ]
  3. { DEFAULT VALUES
  4. | VALUES ( column_values ) [ ,(column_values ... ]
  5. | subquery }
  6. [ ON CONFLICT [ conflict_target ] conflict_action ]
  7. [ returning_clause ]
  8. returning_clause ::= RETURNING { * | { output_expression
  9. [ [ AS ] output_name ] }
  10. [ , ... ] }
  11. column_values ::= { expression | DEFAULT } [ , ... ]
  12. conflict_target ::= ( { column_name | expression } [ , ... ] )
  13. [ WHERE condition ]
  14. | ON CONSTRAINT constraint_name
  15. conflict_action ::= DO NOTHING
  16. | DO UPDATE SET update_item [ , ... ]
  17. [ WHERE condition ]

insert

INSERT - 图1

returning_clause

INSERT - 图2

column_values

INSERT - 图3

conflict_target

INSERT - 图4

conflict_action

INSERT - 图5

Semantics

Constraints must be satisfied.

insert

table_name

Specify the name of the table. If the specified table does not exist, an error is raised.

column_names

Specify a comma-separated list of columns names. If a specified column does not exist, an error is raised. Each of the primary key columns must have a non-null value.

VALUES clause

  • Each of the values list must have the same length as the columns list.
  • Each value must be convertible to its corresponding (by position) column type.
  • Each value literal can be an expression.

ON CONFLICT clause

  • The target table must have at least one column (list) with either a unique indexor a unique constraint. We shall refer to this as a unique key. The argument of VALUESis a relation that must include at least one of the target table’s unique keys.Some of the values of this unique key might be new, and others might already existin the target table.

  • The basic aim of INSERT ON CONFLICT is simply to insert the rows with new values ofthe unique key and to update the rows with existing values of the unique key toset the values of the remaining specified columns to those in the VALUES relation.In this way, the net effect is either to insert or to update; and for this reasonthe INSERT ON CONFLICT variant is often colloquially referred to as “upsert”.

returning_clause

column_values

conflict_target

conflict_action

  1. DO NOTHING | DO UPDATE SET *update_item* [ , ... ] [ WHERE *condition* ]

update_item

condition

Examples

First, the bare insert. Create a sample table.

  1. yugabyte=# CREATE TABLE sample(k1 int, k2 int, v1 int, v2 text, PRIMARY KEY (k1, k2));

Insert some rows.

  1. yugabyte=# INSERT INTO sample VALUES (1, 2.0, 3, 'a'), (2, 3.0, 4, 'b'), (3, 4.0, 5, 'c');

Check the inserted rows.

  1. yugabyte=# SELECT * FROM sample ORDER BY k1;
  1. k1 | k2 | v1 | v2
  2. ----+----+----+----
  3. 1 | 2 | 3 | a
  4. 2 | 3 | 4 | b
  5. 3 | 4 | 5 | c

Next, a basic “upsert” example. Re-create and re-populate the sample table.

  1. yugabyte=# DROP TABLE IF EXISTS sample CASCADE;
  1. yugabyte=# CREATE TABLE sample(
  2. id int CONSTRAINT sample_id_pk PRIMARY KEY,
  3. c1 text CONSTRAINT sample_c1_NN NOT NULL,
  4. c2 text CONSTRAINT sample_c2_NN NOT NULL);
  1. yugabyte=# INSERT INTO sample(id, c1, c2)
  2. VALUES (1, 'cat' , 'sparrow'),
  3. (2, 'dog' , 'blackbird'),
  4. (3, 'monkey' , 'thrush');

Check the inserted rows.

  1. yugabyte=# SELECT id, c1, c2 FROM sample ORDER BY id;
  1. id | c1 | c2å
  2. ----+--------+-----------
  3. 1 | cat | sparrow
  4. 2 | dog | blackbird
  5. 3 | monkey | thrush

Demonstrate “on conflict do nothing”. In this case, we don’t need to specify the conflict target.

  1. yugabyte=# INSERT INTO sample(id, c1, c2)
  2. VALUES (3, 'horse' , 'pigeon'),
  3. (4, 'cow' , 'robin')
  4. ON CONFLICT
  5. DO NOTHING;

Check the result.The non-conflicting row with id = 4 is inserted, but the conflicting row with id = 3 is NOT updated.

  1. yugabyte=# SELECT id, c1, c2 FROM sample ORDER BY id;
  1. id | c1 | c2
  2. ----+--------+-----------
  3. 1 | cat | sparrow
  4. 2 | dog | blackbird
  5. 3 | monkey | thrush
  6. 4 | cow | robin

Demonstrate the real “upsert”. In this case, we DO need to specify the conflict target. Notice the use of theEXCLUDED keyword to specify the conflicting rows in the to-be-upserted relation.

  1. yugabyte=# INSERT INTO sample(id, c1, c2)
  2. VALUES (3, 'horse' , 'pigeon'),
  3. (5, 'tiger' , 'starling')
  4. ON CONFLICT (id)
  5. DO UPDATE SET (c1, c2) = (EXCLUDED.c1, EXCLUDED.c2);

Check the result.The non-conflicting row with id = 5 is inserted, and the conflicting row with id = 3 is updated.

  1. yugabyte=# SELECT id, c1, c2 FROM sample ORDER BY id;
  1. id | c1 | c2
  2. ----+-------+-----------
  3. 1 | cat | sparrow
  4. 2 | dog | blackbird
  5. 3 | horse | pigeon
  6. 4 | cow | robin
  7. 5 | tiger | starling

We can make the “update” happen only for a specified subset of theexcluded rows. We illustrate this by attempting to insert two conflicting rows(with id = 4 and id = 5) and one non-conflicting row (with id = 6).And we specify that the existing row with c1 = ‘tiger’ should not be updatedwith “WHERE sample.c1 <> ‘tiger’“.

  1. INSERT INTO sample(id, c1, c2)
  2. VALUES (4, 'deer' , 'vulture'),
  3. (5, 'lion' , 'hawk'),
  4. (6, 'cheeta' , 'chaffinch')
  5. ON CONFLICT (id)
  6. DO UPDATE SET (c1, c2) = (EXCLUDED.c1, EXCLUDED.c2)
  7. WHERE sample.c1 <> 'tiger';

Check the result.The non-conflicting row with id = 6 is inserted; the conflicting row with id = 4 is updated;but the conflicting row with id = 5 (and c1 = ‘tiger’) is NOT updated;

  1. yugabyte=# SELECT id, c1, c2 FROM sample ORDER BY id;
  1. id | c1 | c2
  2. ----+--------+-----------
  3. 1 | cat | sparrow
  4. 2 | dog | blackbird
  5. 3 | horse | pigeon
  6. 4 | deer | vulture
  7. 5 | tiger | starling
  8. 6 | cheeta | chaffinch

Notice that this restriction is legal too:

  1. WHERE EXCLUDED.c1 <> 'lion'

Finally, a slightly more elaborate “upsert” example. Re-create and re-populate the sample table.Notice that id is a self-populating surrogate primary key and that c1 is a business unique key.

  1. yugabyte=# DROP TABLE IF EXISTS sample CASCADE;
  1. CREATE TABLE sample(
  2. id INTEGER GENERATED ALWAYS AS IDENTITY CONSTRAINT sample_id_pk PRIMARY KEY,
  3. c1 TEXT CONSTRAINT sample_c1_NN NOT NULL CONSTRAINT sample_c1_unq unique,
  4. c2 TEXT CONSTRAINT sample_c2_NN NOT NULL);
  1. INSERT INTO sample(c1, c2)
  2. VALUES ('cat' , 'sparrow'),
  3. ('deer' , 'thrush'),
  4. ('dog' , 'blackbird'),
  5. ('horse' , 'vulture');

Check the inserted rows.

  1. yugabyte=# SELECT id, c1, c2 FROM sample ORDER BY c1;
  1. id | c1 | c2
  2. ----+-------+-----------
  3. 1 | cat | sparrow
  4. 2 | deer | thrush
  5. 3 | dog | blackbird
  6. 4 | horse | vulture

Now do the upsert. Notice that we illustrate the usefulnessof the WITH clause to define the to-be-upserted relationbefore the INSERT clause and use a subselect instead ofa VALUES clause. We also specify the conflict column(s)indirectly by mentioniing the name of the unique constrainedthat covers them.

  1. yugabyte=# WITH to_be_upserted AS (
  2. SELECT c1, c2 FROM (VALUES
  3. ('cat' , 'chaffinch'),
  4. ('deer' , 'robin'),
  5. ('lion' , 'duck'),
  6. ('tiger' , 'pigeon')
  7. )
  8. AS t(c1, c2)
  9. )
  10. INSERT INTO sample(c1, c2) SELECT c1, c2 FROM to_be_upserted
  11. ON CONFLICT ON CONSTRAINT sample_c1_unq
  12. DO UPDATE SET c2 = EXCLUDED.c2;

Check the inserted rows.

  1. yugabyte=# SELECT id, c1, c2 FROM sample ORDER BY c1;
  1. id | c1 | c2
  2. ----+-------+-----------
  3. 1 | cat | chaffinch
  4. 2 | deer | robin
  5. 3 | dog | blackbird
  6. 4 | horse | vulture
  7. 7 | lion | duck
  8. 8 | tiger | pigeon

See also