skipnothing/SQL

Subqueries in Filters

You want every user who never placed an order. You type NOT IN (...), run it, and get back nothing at all: not the one name you expected, not an error, just an empty result.

  • ▸Ask for users with no order via NOT IN, and one guest order with a blank empties the result.
  • ▸A bare JOIN lists Ada twice for her two orders; IN listed her once, so the rewrite needs DISTINCT.
  • ▸Match a single value with = and a second matching row throws an error; IN takes the whole column.
BUILDS ON
01

The Inner Query Runs First

Four rows sit in orders: amounts 42.00, 17.50, 99.00, and a blank cell. You want only the order that hit the highest amount. The highest is a value you don't know yet, so you let a second SELECT find it: SELECT MAX(amount) FROM orders. That runs on its own first, scans the four rows, skips the blank, and comes back with a single number, 99.00. That number is all the outer query ever sees: WHERE amount = 99.00. The result is one row, order 103.

The move is substitution. The query in parentheses, the inner query, runs to completion, collapses to one value, and that value drops into the outer WHERE exactly where you wrote the parentheses, as if you had typed 99.00 yourself. In PostgreSQL's plan, this one-time inner run is labeled InitPlan, and the step inside it that collapses the rows to one value is labeled Aggregate. Because it returns a single row and a single column, it can sit on one side of =; that one-value shape is what makes it a scalar subquery. Change MAX to something that returns several rows and that = has a problem, which is the next move.

THE INNER QUERY COLLAPSES TO ONE VALUE

Keep going, sign up to unlock the rest

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

Sign up, it's freeSee the full SQL