Sub topic 8
Alternatives: IN, EXISTS, and Correlated Subqueries
This chapter assumes you know basic SELECT, WHERE, INNER JOIN, single-table UPDATE and DELETE, table aliases, and primary and foreign keys. The examples use PostgreSQL tables named customers, orders, products, and price_updates.
UPDATE ... FROM and DELETE ... USING are useful when a modification needs columns from another table. Subqueries can express the same row-selection logic without adding another table to the main statement. Choose among them based on whether you need values, only a match test, or a per-row lookup.
Use `IN` when you need a set of keys
IN tests whether a value belongs to a set returned by a subquery. This update cancels open orders belonging to closed customers:
UPDATE orders
SET status = 'cancelled'
WHERE status = 'open'
AND customer_id IN (
SELECT id
FROM customers
WHERE status = 'closed'
);The subquery returns customer IDs. The outer statement updates orders whose customer_id appears in that set.
IN is easy to read when the relationship is one column compared with one column. It does not let the outer statement directly use other columns from the matching customer.
Use `EXISTS` when you only need to test for a match
EXISTS returns true when its subquery produces at least one row. The subquery is usually correlated, which means it refers to a column from the outer row:
DELETE FROM orders AS o
WHERE o.status = 'open'
AND EXISTS (
SELECT 1
FROM customers AS c
WHERE c.id = o.customer_id
AND c.status = 'closed'
);SELECT 1 is conventional because the value does not matter. Only the existence of a matching customer matters.
EXISTS is often a good choice when the related table might contain several matching rows. It still produces only a true-or-false result, so duplicate matches do not duplicate the target row.
Use a correlated subquery when you need one value
A correlated subquery can calculate a value separately for each target row. This example takes the newest staged price for each product:
UPDATE products AS p
SET price = (
SELECT u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id
ORDER BY u.created_at DESC
LIMIT 1
)
WHERE EXISTS (
SELECT 1
FROM price_updates AS u
WHERE u.product_id = p.id
);The EXISTS condition prevents products with no price update from receiving NULL. The ORDER BY and LIMIT make the chosen row explicit. Without them, a subquery that returns several rows causes an error.
Choosing among the alternatives
As a rule, use IN for simple membership, EXISTS for relationship tests, and a correlated subquery when each target row needs a value. Add indexes on the columns used to correlate rows, such as price_updates.product_id and orders.customer_id.
Exercise
Which form should you use to delete customers who have no orders?
Show answer
Use NOT EXISTS: DELETE FROM customers AS c WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.id);