Choose subquery forms for values, membership and presence

Choose scalar, IN, EXISTS, correlated and derived-table forms while keeping cardinality and NULL semantics visible. Subqueries and recursive queries · Databases.

A subquery is a smaller query nested inside a larger one. Its useful question is not “which query runs first?” but “what kind of value does this boundary promise?”

A scalar subquery promises one value, IN supplies a membership set, EXISTS supplies a row-presence test, and a derived table supplies a relation-shaped input. Naming the promise prevents a readable query from carrying a hidden cardinality or NULL bug.

Start with the promised shape

Suppose orders(order_id, account_id, amount, status) records purchases. The main scene uses these account and order rows to compare a candidate order with the paid-order average; the visualisation reveals the returned value and comparison result.

Subquery shapes and NULL-sensitive membership

Read the steps as text

  1. Accounts A7 and A8 and their orders are visible. A paid average, membership relation and grouped relation are named, but no subquery result is shown.
  2. The paid orders average 100. Order O31 has amount 80, so its comparison with that average is FALSE.
  3. A8 NOT IN the nonempty set is UNKNOWN because it has no match and the set contains NULL. NOT IN an empty set is TRUE, even for a NULL left key.
  4. The existence form asks only whether a related paid order can witness the current account. The selected expression is not the returned business value.
  5. The inner predicate refers to the current outer alias. That is a logical dependency; a planner may transform the form without changing the question.
  6. The derived table exposes account_id and total. A7 totals 200 and A8 totals 40, so neither account reaches 1000.
  7. The lesson separates scalar cardinality, NULL-sensitive membership, correlated presence and relation-shaped derived input.

To compare an order with the average paid amount, write a scalar expression such as:

amount > (SELECT AVG(o2.amount)
          FROM orders AS o2
          WHERE o2.status = 'paid')

AVG without GROUP BY returns one row, so this is a good scalar contract. In PostgreSQL, a scalar subquery must return one column and no more than one row: zero rows become NULL, while two rows raise an error. A scalar subquery is therefore not “the first row”; if the data can produce several rows, aggregate, filter, or otherwise make that contract explicit.

For a set of account ids, use membership instead:

WHERE a.account_id IN (
  SELECT o.account_id FROM orders AS o WHERE o.status = 'paid'
)

The inner column is compared with the outer value. IN is a compact OR over equality comparisons. For a nonempty right side, NOT IN has a sharp three-valued-logic edge: if an account does not match any right-side value but the right side contains NULL, the result is UNKNOWN rather than TRUE. A NULL left value is also UNKNOWN in that nonempty case. An empty right-side subquery is the exception: IN is false and NOT IN is true. WHERE keeps TRUE rows only. When the intended question is “no related paid order exists,” prefer the positive counterexample form:

WHERE NOT EXISTS (
  SELECT 1 FROM orders AS o
  WHERE o.account_id = a.account_id AND o.status = 'paid'
)

EXISTS cares whether at least one row survives; the selected expression is conventionally 1 because its value is not the point. NOT EXISTS is an anti-match under its correlation predicate, but it is not a universal NULL policy: a NULL outer key does not equal an inner key, so the outer row may survive. Add an explicit a.account_id IS NOT NULL condition when that is the intended policy. “Accounts that bought every required SKU” is another counterexample pattern: reject an account when a required SKU lacks a matching order, using a nested NOT EXISTS. The inner comparison must still be tied to the current outer account.

Correlation is a dependency, not an execution promise

In the anti-match above, o.account_id = a.account_id refers to the outer alias. That is correlation: the inner predicate depends on the current candidate row. A correlated total can be written as (SELECT SUM(o.amount) FROM orders o WHERE o.account_id = a.account_id). This expresses a per-account logical dependency. It does not prove that the engine literally reruns the text once per row; a planner may decorrelate, join, or aggregate it. Read the data dependency first, then inspect a plan only when performance matters.

A derived table puts the boundary in FROM. For a spend threshold, form a relation before filtering it:

FROM (
  SELECT account_id, SUM(amount) AS total
  FROM orders
  GROUP BY account_id
) AS totals
WHERE totals.total >= 1000

The alias is part of the usable schema. The outer query can see account_id and total, not the hidden intermediate rows. This is different from a scalar total: one produces a relation with potentially many account rows; the other produces one value for comparison. Aggregation subqueries, top-per-group queries, and “maximum per day” examples in the local corpus all rely on making that relation boundary clear.

Faded transfer: make “all” a counterexample

Faded all-features transfer

Read the steps as text

  1. Device D4 and its feature rows are visible beside the required feature relation. The question asks for a completeness rule, not a result yet.
  2. D4 has wifi and gps but lacks required nfc. The missing match is a counterexample, so D4 is rejected.
  3. The same device is now paired with an actually empty required_features relation. The double NOT EXISTS form remains visible, but no classification is shown.
  4. With no required rows, double NOT EXISTS returns TRUE for D4. The product must decide whether to accept that vacuous success.
  5. The faded example keeps the universal question as a search for a missing required witness and names the empty-set policy separately.

The faded scene changes the tables to devices(device_id, owner_id), required_features(feature), and device_features(device_id, feature). To find devices that support every required feature, the logical question is whether there exists a required feature for which no matching device row exists. The query can nest NOT EXISTS twice. It must also state what an empty required set means for the product; vacuous truth may be mathematically sound but surprising as a product rule.

Recap

  • Scalar subqueries need a one-column, at-most-one-row contract; zero rows yield NULL in PostgreSQL.
  • IN is membership, EXISTS is presence, and correlation is an outer-row dependency.
  • A derived table exposes a new relation schema; NOT EXISTS expresses absence and nested counterexamples.
Why the form changes the proof

A scalar average can be checked by cardinality, while a membership predicate can be checked by the right-side set and NULL policy. For the simple SELECT 1 witness shown above, the selected literal does not affect whether a row exists. A derived table needs a named schema and grouping boundary. These are different proofs even when a planner later rewrites them into similar joins.