skipnothing/SQL

EXISTS & Correlated Subqueries

You asked which users never ordered with NOT IN, and one guest checkout with a blank user_id quietly emptied the result. There is a second way to ask that question, one row at a time, that the blank can't touch.

  • ▸For each user, EXISTS asks whether any order matches and needs only the first; one join may answer all users.
  • ▸Add a guest order with a blank user_id: NOT IN empties, NOT EXISTS keeps the unmatched user.
  • ▸PostgreSQL gives IN and EXISTS one plan; an index on the inner column lets both stop reading early.
BUILDS ON
01

The Inner Query Reads Outward

Two tables, the same ones from before. users holds Ada(1), Brent(2), Cleo(3), Dane(4). orders carries rows tagged with user_id 1, 1, 2, 3, so Ada ordered twice and Dane never ordered. The question: which users have placed at least one order?

Last topic answered this by building one list of every user_id and testing membership against it. This time, ask the question per user instead. Take Ada, and run a tiny query just for her: SELECT 1 FROM orders WHERE orders.user_id = users.id, with users.id standing in for Ada's 1. It finds her two orders. Move to Dane, users.id is now 4, and the same inner query, asked for him, finds nothing.

The new piece is orders.user_id = users.id. The inner query reaches up and reads a column from the row the outer query is currently sitting on, so it is no longer self-contained: its answer changes from one outer row to the next. That up-reach, the inner query depending on the current outer row, is the move every later part leans on.

YOU PLUG THE ID, POSTGRESQL ANSWERS PER USER

Keep going, sign up to unlock the rest

3 more parts in this topic, plus 30+ more topics in SQL.

Sign up, it's freeSee the full SQL