NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / RASTERIZEDDB SERVER / MODIFYING DATA

Modifying data

This page covers writing rows: INSERT, upserts with ON CONFLICT, UPDATE, DELETE, MERGE, RETURNING, data-modifying CTEs and bulk loading with COPY. The statements follow PostgreSQL's syntax and behaviour; the exceptions are listed under Limits.

Each statement is atomic: if it fails part-way, none of its changes are kept. Inside a transaction block, a failed statement also aborts the block until you roll back (or roll back to a savepoint). How concurrent writers interact, and how to retry a write conflict (SQLSTATE 40001), is described in Transactions.

Sample tables

The examples use these tables:

sql
CREATE TABLE stock (
    id   INT PRIMARY KEY,
    qty  INT NOT NULL DEFAULT 0,
    note TEXT
);
CREATE TABLE incoming (id INT, qty INT);

INSERT INTO stock VALUES (1, 10, NULL), (2, 20, NULL), (3, 30, NULL);
INSERT INTO incoming VALUES (1, 5), (2, 0), (4, 7);

INSERT

sql
-- Every column, in table order.
INSERT INTO stock VALUES (10, 1, 'first');

-- Named columns; the rest take their defaults (or NULL).
INSERT INTO stock (id, note) VALUES (11, 'no quantity yet');

-- Several rows in one statement.
INSERT INTO stock (id, qty) VALUES (12, 5), (13, 6), (14, 7);

-- DEFAULT for one value, or DEFAULT VALUES for a whole row of defaults.
INSERT INTO stock (id, qty, note) VALUES (15, DEFAULT, 'default qty');
  • The values can be any expressions, including scalar subqueries: VALUES ((SELECT max(id) + 1 FROM stock), 1, NULL).
  • The command tag reports the number of rows written (INSERT 0 3).
  • A value list longer than the column list, or a column the table does not have (42703), is refused before anything is written.
  • INSERT INTO t DEFAULT VALUES inserts one row of defaults; it needs every column to have a default or allow NULL.

INSERT … SELECT

Insert the result of a query. The query can have joins, WHERE, ORDER BY, LIMIT, CTEs, or be a recursive CTE:

sql
INSERT INTO stock (id, qty, note)
SELECT id + 100, qty, 'copied' FROM incoming WHERE qty > 0;

INSERT INTO stock (id, qty)
WITH RECURSIVE r(n) AS (SELECT 200 UNION ALL SELECT n + 1 FROM r WHERE n < 202)
SELECT n, 0 FROM r;

Identity and serial columns

A column declared SERIAL, GENERATED BY DEFAULT AS IDENTITY or GENERATED ALWAYS AS IDENTITY is numbered when you leave it out or write DEFAULT. A GENERATED ALWAYS column refuses a written value (428C9) unless the statement says otherwise:

sql
CREATE TABLE events (id BIGINT GENERATED ALWAYS AS IDENTITY, kind TEXT);

INSERT INTO events (kind) VALUES ('a'), ('b') RETURNING id;
INSERT INTO events (id, kind) OVERRIDING SYSTEM VALUE VALUES (1000, 'imported');
INSERT INTO events (id, kind) OVERRIDING USER VALUE VALUES (5, 'renumbered');

OVERRIDING SYSTEM VALUE keeps the value you wrote; OVERRIDING USER VALUE ignores it and numbers the row. Both work with INSERT … SELECT too. Declaring these columns is covered in Tables and data types.

RETURNING

INSERT, UPDATE, DELETE and MERGE can return the rows they wrote, so you do not need a second query:

sql
INSERT INTO stock (id, qty) VALUES (20, 3) RETURNING id, qty;
UPDATE stock SET qty = qty + 1 WHERE id = 20 RETURNING id, qty - 1 AS before, qty AS after;
DELETE FROM stock WHERE id = 20 RETURNING *;
  • RETURNING *, RETURNING t.*, column names and expressions with aliases all work.
  • An UPDATE returns the row as it is after the update. A DELETE returns the row as it was.
  • INSERT … ON CONFLICT DO NOTHING RETURNING … returns only the rows that were inserted.

Upserts: INSERT … ON CONFLICT

ON CONFLICT decides what happens when a row would break a primary key or unique constraint.

DO NOTHING

Skip the rows that conflict and insert the rest:

sql
INSERT INTO stock (id, qty) VALUES (1, 99), (30, 1) ON CONFLICT DO NOTHING;
text
INSERT 0 1

Without a target, a conflict on any unique constraint is skipped. With a target (ON CONFLICT (id) DO NOTHING), only a conflict on that key is.

DO UPDATE

Update the existing row instead. excluded is the row you tried to insert; the table's own name (or its alias) is the row already there:

sql
INSERT INTO stock (id, qty, note) VALUES (1, 5, 'restocked')
ON CONFLICT (id) DO UPDATE SET qty = stock.qty + excluded.qty, note = excluded.note
RETURNING id, qty, note;
text
 id | qty |   note
----+-----+-----------
  1 |  15 | restocked

A WHERE on the update decides per row whether to update. A row it rejects is left as it was:

sql
INSERT INTO stock AS s (id, qty) VALUES (2, 1)
ON CONFLICT (id) DO UPDATE SET qty = s.qty + excluded.qty
WHERE s.qty < 1000;

The SET list can hold expressions, subqueries and the multi-column form SET (qty, note) = (excluded.qty, 'x').

Choosing the conflict target

TargetMeaning
ON CONFLICT (a, b)The primary key or unique constraint on exactly those columns.
ON CONFLICT ON CONSTRAINT nameA constraint by name, for example stock_pkey.
ON CONFLICT (email) WHERE deleted_at IS NULLA partial unique index with that predicate.
no targetAny unique constraint (DO NOTHING only).

The target must name a unique key exactly. A subset of a composite key, a superset of it, or a column in no key is refused with 42P10, as PostgreSQL refuses it. One statement that proposes the same key twice under DO UPDATE is refused with 21000 ("cannot affect row a second time"), so de-duplicate a batch before you send it.

Upserts under concurrency

Concurrent upserts on the same key never store a duplicate, and each DO UPDATE that reports success was applied exactly once. When two sessions race for the same key, one of them can fail with 40001 (serialization failure) or 40P01 (deadlock). Retry the statement, or the transaction it was in; see Transactions.

UPDATE

sql
UPDATE stock SET qty = qty - 1 WHERE id = 3;
UPDATE stock SET qty = 0, note = 'cleared' WHERE qty < 5;
UPDATE stock SET note = CASE WHEN qty = 0 THEN 'empty' ELSE note END;
UPDATE stock SET qty = DEFAULT WHERE id = 3;
  • Without a WHERE, every row is updated.
  • The new values can be any expressions, including CASE and scalar subqueries that read the row being updated: SET qty = (SELECT sum(qty) FROM incoming i WHERE i.id = stock.id).
  • SET col = DEFAULT writes the column's default; for an identity column it takes the next number.
  • The WHERE can hold IN (SELECT …), EXISTS (…) and correlated subqueries.

Several columns can be assigned from one row of values or one subquery:

sql
UPDATE stock SET (qty, note) = (qty + 10, 'topped up') WHERE id = 2;
UPDATE stock SET (qty, note) = (SELECT 99, 'from query') WHERE id = 3;

UPDATE … FROM

Join other tables into an UPDATE to compute the new values or pick the rows:

sql
UPDATE stock AS s
SET qty = s.qty + i.qty
FROM incoming AS i
WHERE s.id = i.id AND i.qty > 0;

The WHERE must relate the target to its sources. An UPDATE … FROM without a WHERE is refused rather than pairing every row with every other. The target table needs a primary key or a unique column, which is how each joined row is written back.

DELETE

sql
DELETE FROM stock WHERE qty = 0;
DELETE FROM stock WHERE id IN (SELECT id FROM incoming WHERE qty = 0);
DELETE FROM stock s WHERE NOT EXISTS (SELECT 1 FROM incoming i WHERE i.id = s.id);

Without a WHERE, every row is deleted. To empty a table quickly, use TRUNCATE; see Tables and data types.

DELETE … USING

Join other tables into a DELETE to choose the rows:

sql
DELETE FROM stock s
USING incoming i
WHERE s.id = i.id AND i.qty = 0;

As with UPDATE … FROM, the WHERE is required and the target needs a primary key or a unique column. USING can name a CTE:

sql
WITH emptied AS (SELECT id FROM incoming WHERE qty = 0)
DELETE FROM stock s USING emptied e WHERE s.id = e.id;

MERGE

MERGE compares a source with a target and inserts, updates or deletes in one statement. It follows PostgreSQL 17, including WHEN NOT MATCHED BY SOURCE and merge_action():

sql
MERGE INTO stock t
USING incoming s ON t.id = s.id
WHEN MATCHED AND s.qty = 0 THEN DELETE
WHEN MATCHED THEN UPDATE SET qty = t.qty + s.qty, note = 'added'
WHEN NOT MATCHED THEN INSERT (id, qty, note) VALUES (s.id, s.qty, 'new');

Starting from the sample tables, this leaves:

text
 id | qty | note
----+-----+-------
  1 |  15 | added
  3 |  30 |
  4 |   7 | new
  • The source can be a table, a subquery or VALUES with an alias and column list: USING (VALUES (1, 100), (9, 9)) AS s(id, qty).
  • Each source row takes the first WHEN clause whose condition holds. WHEN MATCHED can UPDATE, DELETE or DO NOTHING. WHEN NOT MATCHED [BY TARGET] can INSERT or DO NOTHING. WHEN NOT MATCHED BY SOURCE acts on target rows no source row matched, and can UPDATE, DELETE or DO NOTHING.
  • RETURNING reports each written row; merge_action() gives INSERT, UPDATE or DELETE for it.
  • Matching is done against the target as it was before any action. A target row matched by two source rows fails with 21000.
  • The whole MERGE is one statement: if one action fails, none of them are kept.
sql
MERGE INTO stock AS t
USING (VALUES (1, 100), (9, 9)) AS s(id, qty) ON t.id = s.id
WHEN MATCHED THEN UPDATE SET qty = s.qty
WHEN NOT MATCHED BY TARGET THEN INSERT VALUES (s.id, s.qty, 'v')
WHEN NOT MATCHED BY SOURCE THEN UPDATE SET note = 'stale'
RETURNING merge_action(), t.id, t.qty, t.note;

Data-modifying CTEs

A CTE can be an INSERT, UPDATE or DELETE, usually with RETURNING, and the rest of the statement can read the rows it wrote. The whole statement is one unit: it commits or rolls back together.

sql
CREATE TABLE stock_archive (id INT, qty INT, note TEXT);

WITH gone AS (
    DELETE FROM stock WHERE qty = 0 RETURNING id, qty, note
)
INSERT INTO stock_archive SELECT id, qty, note FROM gone;

WITH added AS (
    INSERT INTO stock (id, qty) VALUES (40, 1), (41, 2) RETURNING id
)
SELECT count(*) FROM added;

A failure inside the CTE is reported with its own SQLSTATE (for example 23505 for a duplicate key), so error handling that branches on the code works.

Bulk loading with COPY

COPY moves many rows in or out in one round trip. It is the fastest way to load data and is what drivers' bulk APIs use (Npgsql's binary import, pgx's CopyFrom, psycopg's copy, JDBC's CopyManager).

sql
COPY stock (id, qty, note) FROM STDIN;
COPY stock FROM STDIN WITH (FORMAT csv, HEADER);
COPY stock (id, qty) TO STDOUT;
COPY (SELECT id, qty FROM stock WHERE qty > 0 ORDER BY id) TO STDOUT WITH (FORMAT csv, HEADER);

COPY runs over PostgreSQL's copy protocol, so the data travels over the client connection. Reading or writing a file or program on the server (COPY t FROM '/path', PROGRAM) is refused with 0A000. From psql, use \copy, which reads and writes files on your machine:

sh
psql "postgresql://app@db.example.com:5432/shop" \
  -c "\copy stock (id, qty, note) FROM 'stock.csv' WITH (FORMAT csv, HEADER)"

Rows loaded with COPY FROM go through the same checks as an INSERT: defaults, NOT NULL, CHECK, unique and foreign keys, triggers and privileges. The load is one statement: if any row fails, none of the rows are kept. Inside a transaction block it is part of the block.

COPY options

Options go in parentheses after WITH (or without WITH). The older spellings (CSV HEADER, BINARY, DELIMITER ',') are accepted too.

OptionDefaultWhat it does
FORMAT text | csv | binarytextTab-separated text, CSV, or PostgreSQL's binary copy format.
HEADER [true | false]offCSV and text: the first line names the columns (skipped on input, written on output). HEADER MATCH is not supported.
DELIMITER 'c'tab (text), , (CSV)The column separator, one single-byte character.
NULL 'string'\N (text), empty unquoted (CSV)The text that stands for NULL.
QUOTE 'c'"CSV quote character.
ESCAPE 'c'"CSV escape character.
FORCE_QUOTE (cols) / FORCE_QUOTE *noneCSV output: quote these columns' values always.
ENCODING 'UTF8'UTF8Only UTF-8 is supported.
FORCE_NOT_NULL, FORCE_NULL, FREEZEAccepted and ignored.

DELIMITER, NULL and HEADER cannot be used with FORMAT binary (42601). COPY … FROM … WHERE is not supported. COPY FROM takes a table; COPY TO takes a table or a query in parentheses.

Limits

These are the differences from PostgreSQL when writing data. Each is refused with an error rather than carried out differently.

  • UPDATE … FROM and DELETE … USING:
    • They need a WHERE.
    • The target needs a primary key or a unique column.
    • A correlated subquery inside an UPDATE … FROM is refused; compute the value in the FROM list instead.
  • An UPDATE with correlated subqueries in both its SET and its WHERE is refused. Move one of them into an UPDATE … FROM.
  • MERGE:
    • Its UPDATE and DELETE actions need a primary key on the target table (0A000).
    • UPDATE SET (a, b) = … inside a MERGE is not supported. Assign each column.
    • OVERRIDING in a MERGE's INSERT is not supported.
  • COPY:
    • Only STDIN and STDOUT; no server-side files or programs.
    • Only UTF-8; no HEADER MATCH; no WHERE.
  • Concurrent upserts on one key can fail with 40001 or 40P01 where PostgreSQL would wait. Retry them.
✓ page rendered in 262 µs axum + tera + htmx · no other javascript