Skip to content

Lab 06 — Query Rewrites

Scenario

A customer query uses a correlated scalar subquery to test whether at least one completed order exists. The requirement is existential, but the query asks PostgreSQL to count matching rows.

Run the exercise

make shell
\i sql/labs/06-rewrites/bad_queries.sql

Investigate

  1. Find the subplan and record how many times it loops.
  2. Distinguish the business requirement from the work expressed by count(*).
  3. Design an equivalent form that can stop after establishing existence.
  4. Confirm equivalent results, including customers with multiple matching orders.
  5. Compare loops, rows, buffers, and elapsed time on repeated runs.

Diagnostic question

What repeated work is caused by correlation, and which equivalent relational expression communicates the requirement more directly?

Previous: Cardinality · Next: Sort and aggregate