smartyfy.mrindigi.com

Databases & SQL Master Course — 107. PostgreSQL INSERT ON CONFLICT

Lesson 107 PostgreSQL INSERT ON CONFLICT

Verification scope and lab safety

PostgreSQL 18 only. These scripts were checked against official documentation but were not executed on that engine in the authoring environment. Every result below is a reasoned expectation, not observed output. Use a dedicated disposable local lab with the required privileges, never an existing application database. No server installation, credential changes, or external database operation is part of this lesson.

Prerequisites and objectives

Complete the constraints and JSONB lessons. You will identify the uniqueness rule that triggers conflict handling, distinguish replacement from accumulation, use a revision guard for stale snapshots, and explain why an upsert does not validate every kind of error or make every replay safe.

Define what a repeated key means

An incoming stock snapshot reports the latest known quantity for one SKU. A newer revision should replace an older snapshot; an older revision should not overwrite newer information. This is different from an event saying that three units were received. Replaying a snapshot may be harmless, while replaying an increment can double-count inventory.

ON CONFLICT supplies a database mechanism for handling a uniqueness conflict. It does not decide which of those business meanings is correct. Start by defining the key, revision ordering, and replacement policy. If two sources can issue incomparable revisions, this simple model is insufficient and needs an explicit source or conflict-resolution design.

Use a declared uniqueness arbiter

The primary key on sku is the conflict arbiter for this lab. Quantity and revision have separate validity rules. We supply explicit SKU values so generated-sequence behavior is not involved. Run all statements in the same disposable local transaction and follow the exercise order, because later checks rely on the newer snapshot installed below.

BEGIN;
CREATE TEMP TABLE lab_stock107 (
 sku text PRIMARY KEY,
 qty integer NOT NULL CHECK (qty >= 0),
 revision integer NOT NULL CHECK (revision > 0)
) ON COMMIT DROP;
INSERT INTO lab_stock107 VALUES ('P1', 4, 2);
INSERT INTO lab_stock107 AS stored (sku, qty, revision)
VALUES ('P1', 7, 3)
ON CONFLICT (sku) DO UPDATE
SET qty = EXCLUDED.qty, revision = EXCLUDED.revision
WHERE EXCLUDED.revision > stored.revision
RETURNING sku, qty, revision;

Read the existing and proposed rows separately

The target alias stored refers to the row already in the table. EXCLUDED refers to the proposed insertion row involved in the conflict. Assigning qty from EXCLUDED.qty replaces the stored snapshot quantity. Assigning stored.qty plus EXCLUDED.qty would instead accumulate, changing the meaning and making repeated delivery significant.

The update condition compares the proposed revision with the stored revision. Equal or older revisions do not qualify. A conflicting row that is not updated because of this condition is not returned by RETURNING. An empty returned result therefore does not necessarily mean a SKU is absent; it can mean that the incoming snapshot was intentionally ignored.

Reasoned snapshot transitions; not observed
Incoming snapshot Policy decision Stored P1
qty 7, revision 3 Replace revision 2 qty 7, revision 3
qty 99, revision 2 Ignore stale revision qty 7, revision 3

The uniqueness rule is essential. A conflict target must match an eligible uniqueness definition; writing ON CONFLICT (sku) does not create that rule. Avoid checking existence in one statement and deciding to insert in another as a substitute for atomic conflict handling. Another writer can change the table between those operations. The statement-level mechanism handles its insert-or-update decision, though applications may still need transaction retries for concurrency failures.

NOT NULL, CHECK, and foreign-key violations are not converted into valid rows by this clause. A negative quantity remains invalid. Treat an upsert as a narrow policy for a declared conflict, not a general instruction to ignore bad data. Also avoid multiple proposed rows that would affect the same target row through one DO UPDATE command.

Worked practice

Exercise 1

Submit an older snapshot and prove that the newer quantity survives.

Worked solution
INSERT INTO lab_stock107 AS stored VALUES ('P1', 99, 2)
ON CONFLICT (sku) DO UPDATE
SET qty = EXCLUDED.qty, revision = EXCLUDED.revision
WHERE EXCLUDED.revision > stored.revision
RETURNING sku, qty, revision;
SELECT sku, qty, revision FROM lab_stock107 WHERE sku = 'P1';

The revision comparison is false, so the existing row remains unchanged. The follow-up SELECT is a lab assertion about final state, not a replacement for obtaining modified rows through RETURNING. In a concurrent application, separate reads must be interpreted under their transaction isolation rules.

Exercise 2

Insert a previously unseen SKU using the same conflict policy.

Worked solution
INSERT INTO lab_stock107 AS stored VALUES ('P2', 3, 1)
ON CONFLICT (sku) DO UPDATE
SET qty = EXCLUDED.qty, revision = EXCLUDED.revision
WHERE EXCLUDED.revision > stored.revision
RETURNING sku, qty, revision;

No uniqueness conflict exists for P2, so the proposed row is inserted. The update condition is relevant to the conflict path, not a general filter that rejects new keys. New rows must still satisfy the required and range constraints.

Exercise 3

Use DO NOTHING for a duplicate P1 and explain what it does not report.

Worked solution
INSERT INTO lab_stock107 VALUES ('P1', 8, 4)
ON CONFLICT (sku) DO NOTHING
RETURNING sku;

The expected returned set is empty because the duplicate is skipped. This policy does not update the quantity to eight, and it does not return the existing P1 row. Use DO NOTHING only when discarding that duplicate is the intended behavior, rather than a shortcut that hides an unresolved update requirement.

Exercise 4

Demonstrate why one DO UPDATE command should not propose the same new key twice.

Worked solution
SAVEPOINT trial;
INSERT INTO lab_stock107 VALUES ('P3', 1, 1), ('P3', 2, 2)
ON CONFLICT (sku) DO UPDATE SET qty = EXCLUDED.qty;
-- Expected error: run recovery below after observing it.
ROLLBACK TO SAVEPOINT trial;
RELEASE SAVEPOINT trial;
SELECT sku, qty FROM lab_stock107 ORDER BY sku;
ROLLBACK;

The command would affect the same target row more than once and is expected to fail. Normalize or reject duplicate input keys using an explicit source policy before the upsert. Do not choose a winner accidentally through input order. Recovery removes the failed command’s work before the final state check.

Pitfalls and summary

A monotonic revision number must be trustworthy within its defined scope. Clock timestamps from unrelated systems may not provide the same ordering guarantee. Equal revisions with different contents also need an audit policy; the simple greater-than guard keeps the stored row but does not prove the sources agree.

Match conflict handling to a real uniqueness rule and an explicit replay contract. Read existing and proposed values separately, distinguish ignored rows from missing rows, and test new, newer, stale, equal, and duplicate-batch cases. The SQL mechanism is powerful because the surrounding business meaning is precise.

Knowledge check

Question 1

Which declaration enables the sku conflict target in this fixture?

  1. The NOT NULL rule on qty
  2. The CHECK requiring a positive revision
  3. The conflict target itself, which creates uniqueness when needed
  4. The primary key on sku
Answer and explanation

D. The primary key supplies the eligible uniqueness rule used to detect the conflict.

Question 2

What does EXCLUDED.qty represent?

  1. The quantity proposed by the attempted insertion
  2. The quantity stored before the attempted insertion
  3. The final quantity after every update expression has run
  4. The conflicting unique-key value converted to a quantity
Answer and explanation

A. EXCLUDED exposes the proposed row involved in conflict handling.

Question 3

What is expected when revision 2 arrives after revision 3 under this policy?

  1. The quantity becomes 99 while the stored revision remains 3
  2. The existing revision 3 row remains unchanged
  3. The stored row is replaced because conflict updates ignore their WHERE clause
  4. The statement raises a duplicate-key error rather than evaluating the revision guard
Answer and explanation

B. The greater-than guard prevents the stale snapshot from replacing newer state.

Question 4

Why is replacing a snapshot different from adding a quantity?

  1. Replacing a snapshot always adds its quantity to the stored amount
  2. A primary key automatically deduplicates repeated increments on that same key
  3. Revision comparison is unnecessary whenever ON CONFLICT is present
  4. Repeating an addition can change the total again
Answer and explanation

D. Replay semantics differ: an increment can be applied twice unless separately deduplicated.

Question 5

What does DO NOTHING RETURNING sku return for the duplicate P1 here?

  1. The existing P1 key as confirmation that the conflict was found
  2. The proposed P1 key even though the row was skipped
  3. No rows
  4. One row containing NULL to distinguish a skip from an empty table
Answer and explanation

C. Skipped rows are not inserted or updated and are not returned by this RETURNING clause.

Dialect verification notes

The target is PostgreSQL 18. Engine execution remains pending. SQLite was not used as a substitute for executing these dialect-specific scripts. Record actual server version, session settings, results, and errors when running the local lab. Python is not a learner prerequisite.

Primary references