Course contents 15 / 17

15 / 17 · Changing Data

Changing rows and handling conflicts

Read the effect of INSERT, UPDATE and DELETE, then resolve a batch to one proposed change per target key.

The shop imports changes to order lines. One file adds a position and changes the quantity of an existing position. The same file may arrive again. Before writing the statements, we need to distinguish the identity of each target row, the value to store and the rule for repeated input.

Select the rows to change#

Start with a temporary table in a fresh PostgreSQL session. This example uses only the position table, with the same key and row rules as in Tables and constraints. The statements below run in order.

CREATE TEMP TABLE order_lines (
    order_id integer,
    line_no integer CHECK (line_no > 0),
    product text NOT NULL,
    quantity integer NOT NULL CHECK (quantity > 0),
    unit_price_cents integer NOT NULL CHECK (unit_price_cents >= 0),
    PRIMARY KEY (order_id, line_no)
);

INSERT INTO order_lines VALUES
    (101, 1, 'tea', 2, 350),
    (101, 2, 'coffee', 1, 600);

INSERT forms new rows. We name the target columns, then supply values in that order. PostgreSQL’s RETURNING clause returns values for affected rows. The following statement stores position 102/1 and returns (102, 1, 1) for its order, position and quantity. PostgreSQL 18, INSERT

INSERT INTO order_lines (
    order_id, line_no, product, quantity, unit_price_cents
) VALUES (102, 1, 'tea', 1, 350)
RETURNING order_id, line_no, quantity;

UPDATE finds existing rows through its condition and sets new column values. The whole key restricts this change to the tea position. With only WHERE order_id = 101, both positions of order 101 would change. For an update driven by a second table with PostgreSQL’s UPDATE ... FROM, each target should match at most one source row. If multiple source rows match, PostgreSQL uses one of them and does not promise which. PostgreSQL 18, UPDATE

UPDATE order_lines
SET quantity = 3
WHERE order_id = 101 AND line_no = 1
RETURNING order_id, line_no, quantity;

The result is (101, 1, 3). DELETE uses a condition to choose which rows to remove. The returned fields are from the deleted row. With no WHERE, these forms of UPDATE and DELETE target every row. PostgreSQL 18, UPDATE and DELETE

DELETE FROM order_lines
WHERE order_id = 101 AND line_no = 2
RETURNING order_id, line_no, product;

This returns (101, 2, 'coffee'). Two lines remain. Position 101/1 has quantity 3 and position 102/1 has quantity 1. The row constraints apply to new and updated values. For example, an update setting quantity to zero fails even when its filter selects the intended row.

Name the conflict that has an alternative#

Suppose the next file provides the full current values for positions 101/1 and 103/1. A plain insert hits the primary key for 101/1. We can specify an alternative for exactly that conflict. PostgreSQL’s ON CONFLICT (order_id, line_no) names the columns of the matching unique key. When an input row conflicts on that key, DO UPDATE applies the assignments to the stored row. EXCLUDED supplies the values of the row proposed for insertion. With a free key, PostgreSQL inserts the proposed row. This pattern is called an upsert. PostgreSQL 18, INSERT

INSERT INTO order_lines AS saved (
    order_id, line_no, product, quantity, unit_price_cents
) VALUES
    (101, 1, 'tea', 4, 350),
    (103, 1, 'cocoa', 2, 400)
ON CONFLICT (order_id, line_no) DO UPDATE
SET product = EXCLUDED.product,
    quantity = EXCLUDED.quantity,
    unit_price_cents = EXCLUDED.unit_price_cents
WHERE (saved.product, saved.quantity, saved.unit_price_cents)
      IS DISTINCT FROM
      (EXCLUDED.product, EXCLUDED.quantity, EXCLUDED.unit_price_cents)
RETURNING order_id, line_no, quantity;
Figure

Two rows of one INSERT

Two rows of one INSERTA conflict on the pair 101, 1 leads to an update. The pair 103, 1 is available, so the row is inserted.(101, 1)Key existsDO UPDATE(103, 1)New keyINSERT
Each input row contains a quantity. The stored row for 101/1 receives 4. Line 103/1 is inserted with quantity 2.

The statement returns 101/1 with quantity 4 and 103/1 with quantity 2, with no requested output order. Position 102/1 stays at 1. The WHERE in the conflict action compares the stored values to the incoming values. IS DISTINCT FROM treats two nulls as equal for this comparison and always returns true or false. If we run the same statement again on the resulting table with no intervening changes, both rows already have the requested values. Both updates are skipped and RETURNING yields zero rows. In PostgreSQL the conflicting rows can still be locked. PostgreSQL 18, INSERT and §9.25.5

Use ON CONFLICT (order_id, line_no) DO NOTHING when an existing row should win without inspecting its contents. It handles the targeted uniqueness conflict. An incoming quantity of zero can still violate the check. The choice to replace, skip or reject a duplicate is part of the import contract.

The quantity assignment above replaces the stored snapshot. If the update used quantity = saved.quantity + EXCLUDED.quantity, the same input of 4 would add 4 each time it was processed. That can be correct for a new increment. For retried increments, the application needs a way to distinguish a previously applied event from a new one.

Choose a single source row per key#

A file can contain two versions of 101/1. PostgreSQL requires that one INSERT ... ON CONFLICT DO UPDATE statement affect any given existing row at most once. For the current table, the following statement raises a cardinality violation. Both proposed rows target the same stored row. Run it separately to observe the error. PostgreSQL 18, INSERT

INSERT INTO order_lines (order_id, line_no, product, quantity, unit_price_cents)
VALUES (101, 1, 'tea', 5, 350), (101, 1, 'tea', 6, 350)
ON CONFLICT (order_id, line_no) DO UPDATE
SET quantity = EXCLUDED.quantity;

Suppose the source defines a higher source_version as newer, and for ties a higher unique event_id as the preferred input. Use the same order in a window function. The partition identifies the target key and ROW_NUMBER() selects one proposed value for it. In this batch, version 8 of 101/1 wins and supplies quantity 6. Position 103/1 has one proposal, which supplies quantity 1.

WITH incoming (
    order_id, line_no, product, quantity, unit_price_cents,
    source_version, event_id
) AS (
    VALUES
        (101, 1, 'tea', 5, 350, 7, 701),
        (101, 1, 'tea', 6, 350, 8, 801),
        (103, 1, 'cocoa', 1, 400, 2, 802)
), ranked AS (
    SELECT *,
           ROW_NUMBER() OVER (
               PARTITION BY order_id, line_no
               ORDER BY source_version DESC, event_id DESC
           ) AS priority
    FROM incoming
)
INSERT INTO order_lines (order_id, line_no, product, quantity, unit_price_cents)
SELECT order_id, line_no, product, quantity, unit_price_cents
FROM ranked
WHERE priority = 1
ON CONFLICT (order_id, line_no) DO UPDATE
SET product = EXCLUDED.product,
    quantity = EXCLUDED.quantity,
    unit_price_cents = EXCLUDED.unit_price_cents
RETURNING order_id, line_no, quantity;

After the statement, positions 101/1, 102/1 and 103/1 have quantities 6, 1 and 1. The ranking resolves competition within this file. The target table has no stored source version, so an older file applied afterward can still overwrite a newer value. To prevent that, a schema can retain the winning source version and tie-break field, then use them to allow only a newer proposal in the conflict action.

The handling of repeated keys varies by dialect. SQLite’s UPSERT makes its choice separately for each input row and can update the same row multiple times in one insert. MySQL 8.4 uses ON DUPLICATE KEY UPDATE, which can react to a duplicate in a primary key or any unique index without the explicit PostgreSQL conflict target. Its manual cautions against using that clause with several unique indexes. Choosing one source row per intended target and documenting the intended uniqueness rule makes those dialect differences visible. SQLite, UPSERT MySQL 8.4, §15.2.7.2

Next#

The import now has a rule for each row. A real operation may also write a receipt and reduce a stock counter. If one statement succeeds and the next fails, the client needs to decide what happens to the successful change. Transactions at the client groups those statements into one operation.

References#

  1. PostgreSQL Global Development Group. PostgreSQL 18 documentation. INSERT, UPDATE, DELETE and row comparisons, §9.25.5 specify target rows, returned values, conflict handling and null-safe comparisons.
  2. SQLite Project. UPSERT, §2. Specifies how conflict handling applies to each proposed row.
  3. Oracle. MySQL 8.4 Reference Manual. INSERT … ON DUPLICATE KEY UPDATE, §15.2.7.2. Describes duplicate-key updates and the behavior with multiple unique indexes.