A correlated subquery references a field from its outer query, so its result can change for each outer row. This contrasts with an uncorrelated subquery, which runs independently and produces one shared result. section 4.3
Maximum power per system
SELECT system_id, read_on, power FROM readings r1 WHERE power = ( SELECT max(power) FROM readings r2 WHERE r2.system_id = r1.system_id ) ORDER BY ALL; The inner query computes a maximum separately for each outer row’s system_id, returning every reading tied for that system’s maximum.
Subqueries also support set comparisons:
- Use EXISTS to test whether a related result exists. section 4.3.1
- Use IN for equality against values returned by a subquery. section 4.3.1
- Use ANY or ALL for inequality or universal comparisons across returned values. section 4.3.1
SELECT avg(sum(kWh)) FROM v_power_per_day GROUP BY system_id
Compare staged aggregation with the correlated pattern when a calculation must vary by outer-row values. section 4.3
