Sub topic 8
Alternatives: IN, EXISTS, and correlated subqueries
This chapter assumes you can write UPDATE ... FROM and DELETE ... USING, and that you know what a subquery is. The examples reuse the customers, orders, products, and price_updates tables from the earlier chapters.
FROM and USING are PostgreSQL extensions to the SQL standard. You can often get the same result with subqueries, which are standard SQL and which work on every major database. The two styles also behave differently when several rows match one target row, and that difference decides which one to use.
Subqueries filter rows, joins can also supply values
A join in UPDATE ... FROM does two jobs. It chooses which target rows to change, and it makes the other table's columns available in SET. A subquery in WHERE does only the first job.
| Need | Joined form | Subquery form |
|---|---|---|
| Choose rows based on another table | `FROM` / `USING` | `IN` or `EXISTS` in `WHERE` |
| Copy a value from another table into `SET` | `FROM` | Scalar subquery in `SET` |
| Choose rows that have no match | Not directly possible | `NOT EXISTS` |
So a DELETE rarely needs USING, because it only needs to filter rows. An UPDATE needs a join or a scalar subquery only when it copies values.
IN with a subquery
IN tests whether a column's value appears in the list returned by a subquery. This statement deletes the same orders as the DELETE ... USING example from earlier:
DELETE FROM orders
WHERE customer_id IN (
SELECT id
FROM customers
WHERE status = 'closed'
);The subquery runs on its own and does not refer to orders. That makes it easy to read and easy to test: paste the subquery into its own SELECT and look at the result.
IN also gives each target row a simple yes-or-no test. If a customer appears in the subquery result twice, the order is still deleted once. A join can repeat a target row once per match, and IN never does.
EXISTS
EXISTS is true when its subquery returns at least one row. The subquery usually refers to the outer table, which makes it a correlated subquery: it is logically evaluated once per outer row.
UPDATE orders AS o
SET status = 'cancelled'
WHERE o.status = 'open'
AND EXISTS (
SELECT 1
FROM customers AS c
WHERE c.id = o.customer_id
AND c.status = 'closed'
);The select list inside EXISTS is ignored, so SELECT 1 is a convention and not a requirement. The alias o on the target table is visible inside the subquery. That visibility is what makes it correlated.
IN and EXISTS usually give the same result. PostgreSQL typically plans both as a semi-join, which stops searching for a match once it finds one. For positive tests, choose whichever reads more clearly. EXISTS is easier when the match needs more than one column, or when several conditions apply to the other table.
Correlated subqueries in SET
A scalar subquery is a subquery that returns one column and at most one row. Placed in SET, it replaces the FROM join and copies a value across:
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 WHERE EXISTS clause is required, not decoration. Without it, the statement visits every product. A product with no staging row gets a subquery that returns no rows, and a scalar subquery with no rows evaluates to NULL. Because products.price is NOT NULL, the whole statement would fail with a not-null violation. On a nullable column, it would instead silently erase the existing values.
Two ways it differs from UPDATE ... FROM
First, the scalar subquery fails loudly if it can return more than one row. If you remove LIMIT 1 and a product has two staging rows, PostgreSQL stops with the error more than one row returned by a subquery used as an expression. UPDATE ... FROM picks one matching row without any warning. Removing the LIMIT 1 therefore turns a silent arbitrary choice into an error you can see. With LIMIT 1 and an ORDER BY, you say explicitly which row wins.
Second, the subquery appears once per column. To copy several columns, you can either write one subquery per column or use PostgreSQL's row form, which assigns a whole row from a single subquery:
UPDATE products AS p
SET (name, price) = (
SELECT 'Renamed ' || p.name, 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 row form runs the subquery once per row instead of once per column, so it is both shorter and cheaper than repeating the subquery for each column.
The NOT IN trap
To select rows that have no match, you might reach for NOT IN. It behaves badly when the subquery can return a NULL. The comparison 1 NOT IN (2, NULL) is not true, because SQL cannot prove that 1 differs from the unknown value. The row is therefore not selected:
SELECT 'kept' AS result
WHERE 1 NOT IN (2, NULL);This query returns zero rows. In a delete, a single NULL in the subquery result makes NOT IN match nothing, and the statement reports DELETE 0 with no error. NOT EXISTS does not have this problem, because it tests whether a row exists instead of comparing values:
DELETE FROM customers AS c
WHERE NOT EXISTS (
SELECT 1 FROM orders AS o WHERE o.customer_id = c.id
);This deletes customers who have no orders. The next chapter covers anti-joins like this one in more depth. For now, remember the rule: prefer NOT EXISTS over NOT IN whenever the subquery column is nullable.
Choosing between the forms
The diagram shows the order of questions to ask.
The same choices as a table:
| Situation | Best choice | Reason |
|---|---|---|
| Simple filter on one other column | `IN` | Shortest, easy to test alone |
| Filter with several conditions on the other table | `EXISTS` | Conditions stay inside the subquery |
| Copy values, one match per row guaranteed | `UPDATE ... FROM` | One join, all columns available |
| Copy values, several matches possible | Scalar subquery with `ORDER BY ... LIMIT 1` | The winner is stated explicitly |
| Rows with no match | `NOT EXISTS` | Safe with `NULL` |
| Code must run on MySQL, SQL Server, or Oracle | `IN` or `EXISTS` | Standard SQL |
Gotchas
- Outer references are easy to get wrong. In
EXISTS (SELECT 1 FROM customers AS c WHERE c.id = o.customer_id), a missing alias lets a column name resolve to the wrong table. Alias every table and qualify every column. - Forgetting the correlation. If the
WHEREinsideEXISTSdoes not mention the outer table, the subquery is either true for all rows or false for all rows. The statement then updates everything or nothing. - Performance. Both forms usually plan well when the matched columns are indexed. A scalar subquery in
SETcan be slower on a large table, because it may run once per updated row. Check withEXPLAINon aSELECTversion before you run a large change. - Testing. Convert the statement to a
SELECTwith the sameWHEREand compare the row count to what you expect. Wrapping the statement inBEGINandROLLBACK, as a later chapter shows, works for both styles.
Exercise
The statement below is meant to set the price of each product to its newest staged price, and to leave products without a staged price alone. It runs without error but gives wrong results on a table where price is nullable. What is wrong, and how do you fix it? UPDATE products AS p SET price = ( SELECT u.newprice FROM priceupdates AS u WHERE u.productid = p.id ORDER BY u.createdat DESC LIMIT 1 );
Show answer
The statement has no WHERE clause, so it visits every product. For a product with no row in priceupdates, the scalar subquery returns no rows and evaluates to NULL, so the existing price is overwritten with NULL. With a NOT NULL column it would fail instead. The fix is to add a filter that matches only products that have a staged price: WHERE EXISTS (SELECT 1 FROM priceupdates AS u WHERE u.product_id = p.id).
Exercise
You run DELETE FROM customers WHERE id NOT IN (SELECT customerid FROM orders); and it reports DELETE 0, although some customers clearly have no orders. The column orders.customerid has since become nullable. Why did nothing get deleted, and what statement fixes it?
Show answer
At least one order has a NULL customerid, so the subquery result contains NULL. For any id, the test id NOT IN (..., NULL) is never true, so no row qualifies. Use NOT EXISTS: DELETE FROM customers AS c WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customerid = c.id);