liveBook · Manning

Nested query

As explained in DuckDB in Action

A subquery is a query nested inside another SQL statement or expression.

A nested query, or subquery, stages part of a SQL computation inside another statement. It separates operations that cannot be directly nested, such as averaging per-system sums. section 4.3

Choose the form that matches the result and comparison:

  • Use an uncorrelated subquery when the inner query is independent of the outer query; it can return multiple rows or one scalar value. section 4.3
  • Use a correlated subquery when the inner query refers to values from the current outer row, such as finding each system's maximum power. section 4.3
  • Use scalar comparisons with exactly one-row results, or use IN, EXISTS, ANY, and ALL for set comparisons. section 4.3.1
  • Prefer arg_min or arg_max for a single expression when they solve the task; use subqueries when selecting several expressions or other conditions. section 4.3

Compute and filter maximum readings

Stage per-system totals before averaging: SELECT avg(sum_per_system) FROM (SELECT sum(kWh) AS sum_per_system FROM v_power_per_day GROUP BY system_id); For per-system maxima, correlate the inner query with the outer row: 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; section 4.3

Listing 4.6 A subquery used with the EXISTS expression
.mode line
SELECT * FROM VALUES (7), (11) s(v)  #1
WHERE EXISTS (SELECT * FROM range(10) WHERE range = v);

Inspect an EXISTS query that keeps values having a match in the inner result. section 4.3.1

How DuckDB in Action covers it

How deep it goes
Explains uncorrelated, scalar, correlated, and set-comparison forms with runnable examples, while deferring broader query optimization.
Examples
Demonstrates per-system power aggregation, maximum-reading filters, correlated maxima, joins, EXISTS, IN, ANY, and ALL.
What it assumes
Assumes basic SELECT, aggregation, WHERE, and comparison syntax while building from simple queries toward analytical SQL.
What you can do after
Apply it in DuckDB to stage aggregates, filter by scalar results, correlate inner queries, and test membership or inequality across result sets.
How it connects
Connects subqueries to aggregate functions, correlated queries, joins, common table expressions, views, and set comparisons.

Also explained in

Compare how 2 books explain nested query →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of DuckDB in Action. The section links point to the parts of the book it draws on.