Sub topic 4
Deleting Based on Another Table with DELETE ... USING
This chapter assumes you know SELECT, WHERE, and INNER JOIN, and that you can write a single-table DELETE. It uses the customers and orders tables from the schema introduced earlier in this tutorial.
Why PostgreSQL has USING instead of JOIN
Standard single-table DELETE removes rows based on that table's own columns. Often the deciding fact lives elsewhere. You might want to delete every order whose customer is closed, but status = 'closed' is a column of customers, not orders.
PostgreSQL has no DELETE ... JOIN. It adds a USING clause that lists extra tables. You then write the join condition in WHERE, just as you would with the old comma-style join in a SELECT.
DELETE FROM orders AS o
USING customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed';This statement:
- Takes
ordersas the target table, the only table that loses rows. - Joins it to
customersusing the conditiono.customer_id = c.id. - Keeps only the combinations where the customer's status is
'closed'. - Deletes the target rows that took part in at least one surviving combination.
Columns from customers can be read in WHERE, but no customers rows are removed.
How the statement is evaluated
Think of the statement as a SELECT over orders JOIN customers, followed by deleting the orders side of each result row. The planner is free to choose a hash join, merge join, or nested loop, just as it would for the equivalent SELECT.
Because the join can produce several result rows for one target row, you may wonder whether it gets deleted twice. It does not. A row is deleted at most once, however many joined rows matched it. That makes DELETE ... USING more forgiving than UPDATE ... FROM, where several matches make the new value ambiguous.
Syntax and rules
The general form is:
DELETE FROM target_table [AS alias]
USING other_table [AS alias] [, another_table ...]
WHERE join_and_filter_conditions
[RETURNING ...];Several rules matter in practice.
- The target table appears in
FROM, and only that table is affected. - Tables in
USINGare read-only for this statement. - You can write
AS oafter the target and give eachUSINGitem its own alias. Aliases keep the join condition readable and avoid ambiguous column names. - Once you alias the target, you must use the alias everywhere in the statement. Writing
orders.idafterFROM orders AS ois an error. - The
USINGlist accepts anything a SELECT'sFROMaccepts: several comma-separated tables, explicitJOIN ... ONclauses, and subqueries.
Here is a version that uses a subquery in USING to pre-filter the customers:
DELETE FROM orders AS o
USING (
SELECT id
FROM customers
WHERE status = 'closed'
) AS c
WHERE o.customer_id = c.id;This is equivalent to the first example. It can be easier to read when the filter on the other table is complex.
A runnable example
Create the tables from the earlier chapter, add sample data, and run the delete.
INSERT INTO customers (id, name, status) VALUES
(1, 'Ada', 'active'),
(2, 'Brook', 'closed'),
(3, 'Chen', 'closed');
INSERT INTO orders (id, customer_id, total, status) VALUES
(10, 1, 25.00, 'open'),
(11, 2, 40.00, 'open'),
(12, 2, 15.50, 'shipped'),
(13, 3, 99.99, 'open');
DELETE FROM orders AS o
USING customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed'
RETURNING o.id, o.customer_id;The statement deletes orders 11, 12, and 13 and returns them. Order 10 stays, because Ada is active. Brook has two orders, and both go in one statement. RETURNING is covered in detail in a later chapter, but it is a convenient way to see what happened.
The missing join condition
The most dangerous mistake is forgetting to connect the two tables. Without a condition linking them, the join is a Cartesian product, where every target row pairs with every USING row.
-- Dangerous: no link between orders and customers
DELETE FROM orders AS o
USING customers AS c
WHERE c.status = 'closed';If at least one customer is closed, every order is paired with that customer, passes the filter, and is deleted. The statement runs without error and removes the whole table. If no customer is closed, it deletes nothing, so the bug can stay hidden until the data changes.
A related mistake is putting the join condition in the wrong place when you use an explicit JOIN inside USING. The ON clause there can only link tables within the USING list. The link between the target table and those tables still belongs in WHERE.
Deleting through several tables
When the deciding fact is two hops away, list both tables and give each a condition. Suppose a table regions held a closed flag and customers pointed to it. The chain would look like this:
DELETE FROM orders AS o
USING customers AS c, regions AS r
WHERE o.customer_id = c.id
AND c.region_id = r.id
AND r.closed;This sketch assumes a regions table with a boolean closed column and a region_id column on customers. Neither exists in the tutorial schema. With N extra tables you need at least N join conditions, or the product grows.
Foreign keys and delete order
USING only decides which rows leave the target table. It does not change how foreign keys behave. If you try to delete customers while orders still reference them, the default NO ACTION rule makes the statement fail.
-- Fails if any closed customer still has orders
DELETE FROM customers WHERE status = 'closed';You have two ways to handle this. Delete the child rows first with the DELETE ... USING statement shown above, then delete the parents. Or declare the foreign key with ON DELETE CASCADE, so deleting a customer removes its orders automatically. Cascading is convenient, but it makes the effect of a delete less visible, so use it deliberately.
Choosing between USING and a subquery
DELETE ... USING is a good fit when:
- you need columns from the other table in
WHEREfor a join-style filter; - you want the join to read like the SELECT you would use for a preview;
- the relationship is a plain inner join.
It is the wrong tool when you need to delete rows that have no match. USING only produces matched combinations, so an orphaned row never appears in it. That case needs NOT EXISTS, which a later chapter covers. For a simple "is there any match" test, WHERE o.customer_id IN (SELECT id FROM customers WHERE status = 'closed') gives the same result as the join and avoids any thought about multiplicity.
Common errors
| Symptom | Likely cause |
|---|---|
| Whole table deleted | No join condition between target and `USING` tables |
| `missing FROM-clause entry for table "orders"` | The target was aliased but the original name is used in `WHERE` |
| `column reference "id" is ambiguous` | Both tables have an `id` column and one reference is unqualified |
| `violates foreign key constraint` | Child rows still reference the rows being deleted |
| Zero rows deleted | The join condition never matches, or the filter excludes everything |
Exercise
Table orders has an status column, and customers has a status column. Write a statement that deletes all orders with status 'cancelled' whose customer has status 'closed'. Then explain what would happen if you left out the line that compares o.customer_id to c.id.
Show answer
DELETE FROM orders AS o USING customers AS c WHERE o.customer_id = c.id AND o.status = 'cancelled' AND c.status = 'closed'; Without the join line, every order is paired with every customer. If any customer is closed, every cancelled order is deleted, including those belonging to active customers. If no customer is closed, nothing is deleted.
Exercise
A DELETE ... USING statement joins one order to a customer row that matches. If a target row matched three joined rows, how many times is it deleted, and why does this differ from UPDATE ... FROM?
Show answer
It is deleted once. A row can only be removed one time, so extra matches change nothing. In UPDATE ... FROM, each match could supply a different new value, so PostgreSQL picks one arbitrarily and the result is unpredictable.