Search RU
Tasks / SQL / Idempotent order upsert
Statement medium

Idempotent order upsert

Create order `101` or update it if it already exists. Values:
`customer_id = 7`, `total = 4990`, `status = 'paid'`.

Running it twice must not create a duplicate. Other orders stay unchanged.

SQL · PostgreSQL
sqlinsertupserton-conflict
Schema
CREATE TABLE orders (
    id integer PRIMARY KEY,
    customer_id integer NOT NULL,
    total integer NOT NULL,
    status text NOT NULL,
    updated_at timestamptz NOT NULL DEFAULT now()
);
Data
INSERT INTO orders (id, customer_id, total, status) VALUES
    (101, 7, 1000, 'new'),
    (102, 8, 2000, 'new');
query.sql PostgreSQL 17
AI mentor

The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.

Log in and ask
Hints 1 of 3 unlocked · attempts: 0
Hint 1

You need one operation that both creates a row and updates an existing one,
not separate `INSERT` and `UPDATE` statements.

Hint 2 — unlocks after 1 attempt
Hint 3 — unlocks after 3 attempts