System design Level 2 This level · 21 of 48
Medium postgresql sql

When do you use EXISTS, IN or a JOIN, and why is NOT IN dangerous?

The 30 second answer

For "customers who placed an order", EXISTS and IN both express a semi-join and PostgreSQL usually plans them the same way; a plain JOIN can duplicate customers with several orders, so it needs DISTINCT. For "customers with no orders", use NOT EXISTS. NOT IN returns no rows at all if the subquery contains a NULL, and the planner can't turn it into an anti-join, so it can become very slow on large data.

Could you say this in an interview?

From the basics. "Customers who bought something" is a semi-join: return each customer once if at least one matching order exists. "Customers who never bought" is an anti-join.

Duplicates with JOIN.

-- Wrong: one row per order, not per customer
SELECT c.id, c.email FROM customers c JOIN orders o ON o.customer_id = c.id;

-- Right: semi-join
SELECT c.id, c.email FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

IN (SELECT customer_id FROM orders) expresses the same thing and is usually planned the same way in PostgreSQL (a semi-join in EXPLAIN). Pick whichever reads better; EXISTS is clearer when the condition has several columns.

The NOT IN trap. The PostgreSQL docs: "if there are no equal right-hand values and at least one right-hand row yields null, the result of the NOT IN construct will be null, not true." So:

-- Returns zero rows if any orders.customer_id is NULL
SELECT id FROM customers WHERE id NOT IN (SELECT customer_id FROM orders);

-- Correct and plannable as an anti-join
SELECT c.id FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

The PostgreSQL wiki's "Don't Do This" page adds the performance reason: "the planner can't transform it into an anti-join", so it becomes a hashed subplan (fast, but only allowed for small result sets) or a plain subplan that is "horrifically slow (in fact O(N²))". It warns that performance "can look good in small-scale tests" and then collapse once a size threshold is crossed.

Trade-offs.

  • LEFT JOIN ... WHERE o.id IS NULL is another correct anti-join and plans similarly to NOT EXISTS. NOT EXISTS states the intent more clearly.
  • For a short literal list, IN (1, 2, 3) or = ANY($1) with an array parameter is fine and index-friendly.
  • Correlated subqueries in the SELECT list (one per row) are a different pattern; rewrite them as joins or LATERAL when they run for many rows.

Alternate interview scenarios

"A cleanup job deleting products NOT IN (SELECT product_id FROM order_items) deletes nothing."

Some product_id values are NULL. Use NOT EXISTS.

"Find products that were never ordered in the last 90 days, fast."

NOT EXISTS with a date condition inside the subquery, and an index on order_items(product_id) plus the date column on orders.

"Orders and order lines both have a status. Close an order only when all its lines are closed, efficiently."

"All lines closed" is the same as "no open line exists", so this is an anti-join and I write it with NOT EXISTS. I avoid comparing COUNT(*) of all lines with a count of closed lines, because that reads every line of every order. A partial index that holds only open lines keeps the check to one small index probe per order. It also stays small as closed history grows, since closed lines never enter it.

CREATE INDEX order_lines_open_idx ON order_lines (order_id)
WHERE status <> 'CLOSED';

UPDATE orders o
SET status = 'CLOSED'
WHERE o.status <> 'CLOSED'
  AND NOT EXISTS (SELECT 1 FROM order_lines l
                  WHERE l.order_id = o.id AND l.status <> 'CLOSED');

Two details I'd mention. First, status should be NOT NULL: a line with a NULL status makes status <> 'CLOSED' evaluate to null, so that line silently counts as closed. Second, in an event-driven system I run the same statement for one order id right after closing a line, in the same transaction. If lines can also be reopened, both paths lock the order row first with SELECT ... FOR UPDATE, so a reopen can't slip in between the check and the update.

Sources (3)
  1. PostgreSQL docs: Subquery expressions (EXISTS, IN, NOT IN)postgresql.org
  2. PostgreSQL wiki: Don't Do This (Don't use NOT IN)wiki.postgresql.org
  3. PostgreSQL 17 docs: Partial indexespostgresql.org
Previous
Next