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
Investigate
- Find the subplan and record how many times it loops.
- Distinguish the business requirement from the work expressed by
count(*). - Design an equivalent form that can stop after establishing existence.
- Confirm equivalent results, including customers with multiple matching orders.
- 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?