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.
Code
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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Which relations are involved here?
- `customers`, `orders`, `of`, `order` — joined via 2 JOIN clauses.
Report a problem with this exampleOpens a pre-filled issue on GitHub.