Insert Update Delete
Write paths with DML and RETURNING. Results appear in the same fence: same-line -- comments when short, multiline -- blocks below the sample when not.
Busque em todas as páginas da documentação
Write paths with DML and RETURNING. Results appear in the same fence: same-line -- comments when short, multiline -- blocks below the sample when not.
Insert and return generated columns.
INSERT INTO users (email) VALUES ('a@b.co')
RETURNING id, created_at;
-- id | created_atUpdate from another table/source.
UPDATE orders o
SET status = 'paid'
FROM payments p
WHERE p.order_id = o.id AND p.ok;
-- mark paid ordersDelete with a join-like USING.
DELETE FROM sessions s
USING users u
WHERE s.user_id = u.id AND u.banned;
-- drop banned users' sessionsInsert or update on unique violation.
INSERT INTO kv (k, v) VALUES ('a', 1)
ON CONFLICT (k) DO UPDATE
SET v = excluded.v
RETURNING *;
-- upserted rowBulk insert from a query.
INSERT INTO archive
SELECT * FROM events WHERE created_at < now() - interval '90 days';
-- rows inserted: nSee old/new values after update.
UPDATE users SET name = 'Ada'
WHERE id = 1
RETURNING id, name;
-- 1 | AdaCapture deleted rows.
DELETE FROM jobs WHERE done
RETURNING id;
-- deleted idsOmit columns to use defaults.
INSERT INTO t DEFAULT VALUES RETURNING *;
-- row with defaultsInsert several tuples at once.
INSERT INTO tags (name) VALUES ('a'), ('b'), ('c');
-- 3 rowsIgnore duplicates.
INSERT INTO emails (addr) VALUES ('x@y.z')
ON CONFLICT DO NOTHING;
-- 0 or 1 rowCareful: no WHERE updates entire table.
UPDATE products SET updated_at = now();
-- all products touchedWITH ... INSERT/UPDATE/DELETE.
WITH doomed AS (
SELECT id FROM jobs WHERE attempts > 5
)
DELETE FROM jobs j USING doomed d WHERE j.id = d.id;
-- purge retriesSQL MERGE for conditional insert/update (PG 15+).
MERGE INTO target t
USING source s ON t.id = s.id
WHEN MATCHED THEN UPDATE SET v = s.v
WHEN NOT MATCHED THEN INSERT (id, v) VALUES (s.id, s.v);Bulk load from file/stdin - fastest ingest.
-- COPY t (a,b) FROM '/tmp/t.csv' WITH (FORMAT csv, HEADER true);
-- rows loaded: nDrop all rows fast; reset identity optional.
TRUNCATE TABLE staging RESTART IDENTITY;
-- staging emptyStack versions: PostgreSQL 18.4 (stable 18, maintenance 17) · pgvector 0.8+
Revisado por Chris St. John·Última atualização: 18 de jul. de 2026