For Update Of Targets One Table

FOR UPDATE OF o locks only the listed table rows in a join; without OF every participating table gets row locks, including pure filter-side tables.

SqlResilience

Code

snippet
CREATE TABLE orders (
    id          int PRIMARY KEY,
    customer_id int NOT NULL,
    status      text NOT NULL
);

CREATE TABLE customers (
    id   int PRIMARY KEY,
    name text NOT NULL
);

INSERT INTO customers VALUES (1, 'ada'), (2, 'raj');
INSERT INTO orders VALUES (100, 1, 'paid'), (101, 2, 'pending');

-- FOR UPDATE OF:只锁 orders 的行;customers 只参与过滤,不加行锁
SELECT o.id, o.status, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'pending'
FOR UPDATE OF o
ORDER BY o.id;

-- 不带 OF:join 的两张表行都加锁(每表各取一行)
SELECT o.id, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.id = 100
FOR UPDATE
ORDER BY o.id;

How the snippet works

What runs here is SELECT / INSERT / UPDATE / CREATE — customers, orders, of and order are the objects involved.

Mechanically, the statements are built from: 2 JOINs combining rows across tables; a WHERE clause filtering the rows one statement applies to; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

What to watch for

  • Row counts compound across 2 joins; make sure the join keys are indexed before adapting this to production data volumes.

Using it

The customers table is the working surface here.

Key statements

SELECT o.id, o.status, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'pending'
FOR UPDATE OF o
ORDER BY o.id;
SELECT o.id, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.id = 100
FOR UPDATE
ORDER BY o.id;
CREATE TABLE orders (
    id          int PRIMARY KEY,
    customer_id int NOT NULL,
    status      text NOT NULL
);

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`customers`, `orders`, `of`, `order` — joined via 2 JOIN clauses.