SQL Subqueries and CTEs: Set Operations

Answer questions that take more than one step in a single SQL statement. Nest one query inside another to compute a value, a list or a temporary table; compare each row with figures from related rows using correlated subqueries; and test whether matching rows exist with EXISTS. Combine result sets with UNION, INTERSECT and EXCEPT. Then organize long queries as named, testable steps with common table expressions, and use recursive CTEs to walk hierarchies such as an organization chart, a chain of prerequisites or a parts list.

IntermediateLesson 1 of 8 in Database Design and Advanced SQL Course

What you will learn

  1. Place one query inside another to compute a value, a list or a temporary table, and use that result to filter or extend the outer query.
    • Compute a single value with a scalar subquery
      Recognize what a subquery is, write subqueries that return exactly one value, and use them in WHERE, HAVING and SELECT.
    • Use a subquery as a table in FROM
      Treat the result of a query as a temporary table, a derived table, then name it and query it again to aggregate in two stages, filter on computed columns or join back for details.
    • Filter with IN, NOT IN, ANY and ALL
      Compare a value with the list a subquery returns, use ANY and ALL for comparisons other than equality, and avoid the NULL trap of NOT IN.
  2. Write subqueries that depend on the current row of the outer query, test whether related rows exist, and decide when a join or a subquery fits the question better.
    • Write correlated subqueries
      Link an inner query to each row of the outer query to compare a row with its own group or to compute a value for each row.
    • Test for related rows with EXISTS and NOT EXISTS
      Use EXISTS to keep rows that have a match and NOT EXISTS to keep rows that have none, including questions of the form "for every".
    • Choose between a join and a subquery
      Rewrite a query between join and subquery forms, and pick the form that returns the right rows and states the question most clearly.
  3. Stack, intersect and subtract the results of two queries with UNION, INTERSECT and EXCEPT, and control duplicates, column matching and the order of evaluation.
    • Stack results with UNION and UNION ALL
      Combine the rows of two compatible queries into one result, decide whether duplicates should stay, and sort or label the combined rows.
    • Find shared and missing rows with INTERSECT and EXCEPT
      Return the rows two queries have in common or the rows of one query that are missing from another, and handle NULLs, duplicates and the order of evaluation.
  4. Name the steps of a long query with WITH, chain and reuse them, and solve multi-step questions one tested step at a time.
    • Define and chain CTEs
      Write WITH clauses with one or several named steps, reference earlier steps from later ones, and know how long a CTE exists and how systems differ.
    • Solve a multi-step question in named steps
      Break a question into intermediate results, write each as a CTE, check each step, and combine them into a correct final answer.
  5. Use recursive common table expressions to generate sequences and to follow parent-child links through trees and graphs, and stop recursion safely when the data contains cycles.
    • Build a recursive CTE
      Write the anchor and recursive members, trace how the rows are produced step by step, and make the recursion stop.
    • Walk trees and graphs with recursion
      Follow parent-child links down to all descendants and up to all ancestors, track depth and path, and handle items with several parents and quantities that multiply along a path.
    • Prevent infinite recursion and handle cycles
      Recognize when recursion would never end, use system limits as a safety net, and stop at cycles by tracking visited rows or depth.

SQL Subqueries and CTEs study guide

5 chapters

1

Answer questions with nested subqueries

A query can use the result of another query as a value, a list, or a table. The shape of that inner result determines where it fits and which operators can use it. Start with an overall average, then build a table of grouped values and compare a row with a list. These examples also show why an empty result, a second row, or a NULL can change the answer even when the SQL looks almost the same.

1.1 Compute a single value with a scalar subquery

A subquery is a query nested in another statement. Its result fills a particular role in the outer query. Before writing it, decide what shape that role needs.

Match the result to its position
ShapeResultTypical use
ScalarOne column, at most one rowA comparison or computed value
ColumnOne column, any number of rowsAn IN list
RowSeveral columns, at most one rowA row-value comparison
TableAny number of rows and columnsA table in FROM

A scalar subquery belongs in parentheses wherever a single value is allowed. Its query can use aggregation even when the surrounding query is testing individual rows.

Compare products with the overall average

The shop stores prices as NUMERIC(10, 2). Its products(product_id, name, category, price) table contains Notebook 4.00 and Pen set 6.00 in stationery, Desk lamp 25.00 and Mug 8.00 in home, and Backpack 40.00 and Tote bag 12.00 in bags. Ask: "Which products cost more than the average price?"

SELECT name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products);

First read the inner query: the six prices total 95.00, so their average is 95.00 divided by 6, approximately 15.83. Then test each outer price against that value. Desk lamp and Backpack qualify. The query uses the full computed average; 15.83 is just its displayed rounding.

WHERE price > AVG(price) cannot do this job at one query level. WHERE filters individual rows before that level's aggregation. The inner query creates a separate level where the average can be computed. Hard-coding 15.83 would also lose the link to the data when prices change.

Use the value in other clauses

A scalar subquery in SELECT can extend each row:

SELECT name,
       price - (SELECT AVG(price) FROM products) AS diff_from_avg
FROM products;

The differences, rounded to two decimals, are Notebook −11.83, Pen set −9.83, Desk lamp 9.17, Mug −7.83, Backpack 24.17, and Tote bag −3.83. A positive result means the price is above the overall average.

To compare category averages with that same overall figure, filter the groups with HAVING:

SELECT category, AVG(price) AS avg_price
FROM products
GROUP BY category
HAVING AVG(price) > (SELECT AVG(price) FROM products);

Home averages 16.50 and bags 26.00, so both qualify. Stationery averages 5.00 and does not.

Check zero rows and multiple rows

A scalar subquery with no rows produces NULL. There is no product named "Lamp", so (SELECT price FROM products WHERE name = 'Lamp') gives NULL. Comparing a price with it gives unknown; WHERE keeps only true conditions.

An aggregate without GROUP BY still returns one row over empty input: COUNT(*) gives 0, while AVG, SUM, MIN, and MAX give NULL.

A scalar subquery must not return two rows. Selecting prices for category 'home' returns both 25.00 and 8.00. PostgreSQL, MySQL, SQL Server, and Oracle reject using that result as one value. SQLite takes a first row, which can hide the error. Repair the intended question: match any price with IN, compute one value with an aggregate, or select by a unique key.

Key Takeaways

  • A scalar subquery supplies one value; zero rows produce NULL.
  • Use a separate query level to compare rows or groups with an overall aggregate.
  • A scalar subquery must not return multiple rows, even if SQLite accepts it.
  • Over empty input, COUNT(*) gives 0; the other common aggregates give NULL.

1.2 Use a subquery as a table in FROM

An inner query can produce a table for an outer query to read. This derived table gives a multi-step calculation a clear boundary: the inner query builds rows, and the outer query works with those rows.

The shop's customer and order rows

customers(customer_id, name, city) contains 1/Ana/Lisbon, 2/Ben/Toronto, 3/Chen/Singapore, 4/Dara/Lisbon, and 5/Eli/Nairobi. The order table is orders(order_id, customer_id, order_date, amount), with amount stored as NUMERIC(10, 2):

order_idcustomer_idorder_dateamount
10112026-03-0230.00
10222026-03-0512.00
10312026-03-0945.00
10432026-03-158.00
10522026-03-2064.00
10612026-04-0110.00
Aggregate in two stages

The shop's orders belong to three customers. Ana has three orders, Ben two, and Chen one. Dara and Eli have none. To find the average order count among customers with orders, first count each customer's orders:

SELECT AVG(order_count) AS avg_orders
FROM (
  SELECT customer_id, COUNT(*) AS order_count
  FROM orders
  GROUP BY customer_id
) per_customer;

The derived table has rows (1, 3), (2, 2), and (3, 1). The outer average is 2.0. Writing AVG(COUNT(*)) at the same query level is rejected by PostgreSQL, MySQL, SQL Server, and SQLite: the count results need their own query level before they can be averaged.

Name the derived table and its computed columns. The alias per_customer names the result; order_count names the value the outer query averages. An alias without AS works across the systems used here. Oracle rejects AS before a table alias. MySQL and SQL Server require a derived-table alias; PostgreSQL made it optional in version 16.

Filter a computed column

An alias from a SELECT list is generally unavailable to WHERE at that same query level. Wrapping the calculation makes it an input column of the outer query:

SELECT customer_id, total
FROM (
  SELECT customer_id, SUM(amount) AS total
  FROM orders
  GROUP BY customer_id
) totals
WHERE total > 50;

Customer totals are Ana 85.00, Ben 76.00, and Chen 8.00. The filter returns Ana's and Ben's IDs and totals. For this simple group filter, HAVING SUM(amount) > 50 also works. SQLite permits some same-level aliases in WHERE as an extension; the wrapper gives the alias a separate query level in every system.

Join a computed result back to detail rows

A maximum date alone does not supply the rest of its order's columns. Build one maximum per customer, then join on both the customer and date:

SELECT o.order_id, o.customer_id, o.order_date
FROM orders o
JOIN (
  SELECT customer_id, MAX(order_date) AS last_date
  FROM orders
  GROUP BY customer_id
) latest
  ON latest.customer_id = o.customer_id
 AND latest.last_date = o.order_date;

This returns orders 106, 105, and 104. Joining on the date alone could attach another customer's order from that date. When one customer has two orders tied on the latest date, both qualify; the query does not choose between ties.

Where row values are supported, the same pair can be tested with (customer_id, order_date) IN (SELECT customer_id, MAX(order_date) FROM orders GROUP BY customer_id). That subquery returns several rows of two columns. A single-row comparison instead uses = and a subquery restricted to one order. SQL Server lacks these row-value forms; use the join there.

Decide who belongs in the average

The first example averages three customers, because starting from orders leaves out customers with no orders. An average over all five customers needs a different inner table: start from customers, left join orders, and use COUNT(o.order_id) to give unmatched customers zero. Their counts are 3, 2, 1, 0, 0, so the average is 1.2. Use AVG(1.0 * order_count) to preserve fractional averages in SQL Server, where AVG of integer counts returns an integer. COUNT(*) would count each unmatched customer's padded row as one.

Key Takeaways

  • A derived table creates a new query level with named input columns.
  • Use two query levels for an average of grouped counts.
  • Join on the group key and the computed maximum to recover detail rows, including ties.
  • Row-value comparisons need matching column counts and database support.
  • Start from the full population when rows with no matches must count as zero.

1.3 Filter with IN, NOT IN, ANY and ALL

A list subquery lets one value be tested against many rows. Membership and comparison operators differ in what they require from that list, especially when it is empty or contains NULL.

Membership keeps outer rows
SELECT name
FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders);

The inner list is 1, 2, 1, 3, 2, 1. The outer query returns Ana, Ben, and Chen once each. Repeating an ID in the list does not repeat an outer row. A join would return one row per matching order instead.

NOT IN asks whether the value differs from every list value. With the order IDs above, it returns customers Dara and Eli, who have no orders.

Follow the NULL trap

In employees(employee_id, name, manager_id), Maya has no manager, Omar and Lena report to Maya, Raj and Sofia report to Omar, and Tom reports to Raj. Their manager IDs are NULL, 1, 1, 2, 2, 4.

SELECT name
FROM employees
WHERE employee_id NOT IN (SELECT manager_id FROM employees);

This returns nobody. Lena's ID 3 differs from each known manager ID, but 3 <> NULL is unknown. All comparisons must be true for NOT IN to be true. IDs that do match a manager ID fail the test anyway.

Remove nulls inside the subquery with WHERE manager_id IS NOT NULL, or express the absence of a matching row with correlated NOT EXISTS. Both return Lena, Sofia, and Tom. IN can still be true when a matching known value exists beside a null; without a match, it can be unknown. WHERE rejects unknown as well as false.

Compare with any or all values
TestMeaningStationery list 4.00, 6.00
price > ANY (...)Greater than at least one valueKeeps prices above 4.00
price > ALL (...)Greater than every valueKeeps prices above 6.00
price = ANY (...)Equal to at least one valueSame as IN
price <> ALL (...)Different from every valueSame as NOT IN

SOME is another spelling of ANY. <> ANY means different from at least one value; it does not mean absent from the list. Pen set at 6.00 passes > ANY but fails > ALL; Desk lamp, Mug, Backpack, and Tote bag pass both.

With an empty list, ANY is false and ALL is true. No comparison succeeds for ANY; no comparison fails for ALL. This is why replacing > ALL with > MAX(...) changes an empty-list result: MAX returns NULL over no rows.

Preserve the conditions when rewriting

For a nonempty list of non-null numbers, > ALL can be replaced by a comparison with the list's maximum. With nulls, MAX ignores them, while ALL cannot be true if any comparison is unknown.

In PostgreSQL, this filter keeps only rows for which every comparison is true, including the empty-list case:

WHERE NOT EXISTS (
  SELECT 1 FROM products s
  WHERE s.category = 'stationery'
    AND (p.price > s.price) IS NOT TRUE
)

It preserves which rows a WHERE ... > ALL filter keeps; it turns both false and unknown cases into rejection. SQL Server needs a different spelling of the Boolean test.

PostgreSQL, MySQL, SQL Server, and Oracle support subquery ANY and ALL; SQLite does not. A single-column left value needs a single-column subquery. Multi-column IN requires a matching row value: MySQL supports it, but not row-valued ANY or ALL; SQL Server supports none of those row-value forms.

Key Takeaways

  • IN tests membership without multiplying outer rows.
  • A null in a scalar NOT IN list prevents the test from being true.
  • ANY needs one successful comparison; ALL needs every comparison to be true.
  • Over an empty list, ANY is false and ALL is true.
  • <> ANY is not an absence test.
  • A maximum-based rewrite needs a nonempty, null-free list.
2

Compare rows with correlated subqueries and existence tests

Some questions need a different comparison for each row: a product's own category average, a customer's own orders, or a student's own missing courses. Correlated subqueries express those relationships by linking the inner query to the current outer row. Existence tests then turn those links into clear questions about matches. Rewriting them as joins requires care with duplicate rows, shared names, and missing matches.

2.1 Write correlated subqueries

A correlated subquery refers to the outer row. Its answer can change as that row changes. An uncorrelated subquery is self-contained: the same inner query can be run on its own.

Compare a product with its own group
SELECT p.name, p.category, p.price
FROM products p
WHERE p.price > (
  SELECT AVG(p2.price)
  FROM products p2
  WHERE p2.category = p.category
);

p is the product currently being tested. p2 ranges over products in the inner query. The condition p2.category = p.category restricts the average to the current product's category.

For Notebook, the inner query averages stationery prices 4.00 and 6.00: 5.00. Notebook fails the comparison and Pen set passes it. Home averages 16.50, so Desk lamp passes and Mug fails. Bags averages 26.00, so Backpack passes and Tote bag fails. The result is Pen set, Desk lamp, and Backpack.

Removing the correlation changes the question to the overall average, about 15.83, and leaves only Desk lamp and Backpack. Row-by-row substitution explains the meaning of correlation; it does not require the database to execute a separate physical query for every row.

Make every column's owner clear

Qualify columns with aliases, especially when the same table appears twice. An unqualified name is resolved first against tables in the nearest query scope, then against outer scopes.

SELECT name
FROM customers
WHERE customer_id IN (
  SELECT customer_id FROM products
);

Although products has no customer_id, this can run: the inner name resolves to the outer customer's ID. Since products is nonempty, each customer's own ID appears in that customer's inner result. All five customers qualify. Writing SELECT p.customer_id FROM products p exposes the nonexistent column as an error.

Compute one result per outer row
SELECT c.name,
       (SELECT COUNT(*) FROM orders o
        WHERE o.customer_id = c.customer_id) AS order_count
FROM customers c;

This keeps every customer and returns Ana 3, Ben 2, Chen 1, Dara 0, and Eli 0. COUNT(*) over the inner query's empty input gives zero. Replacing it with MAX(o.order_date) gives Ana 2026-04-01 and gives Dara and Eli NULL.

A left-join rewrite must count o.order_id, not *. An unmatched customer still has one padded join row; COUNT(*) would report one order for that customer.

Keep ties in greatest-per-group queries

Replace the inner AVG with MAX and the outer comparison with = to get the most expensive products per category. Pen set, Desk lamp, and Backpack qualify; an added product tied at the maximum would qualify too. Selecting name beside MAX(price) while grouping only by category cannot reliably identify a product row; PostgreSQL, SQL Server, and default MySQL reject that shortcut.

The pattern also applies within orders. Compare each order with AVG(o2.amount) where o2.customer_id = o.customer_id. Ana's average is about 28.33, Ben's is 38.00, and Chen's is 8.00. Orders 101 at 30.00, 103 at 45.00, and 105 at 64.00 qualify. Chen's order equals its group average, so strict > excludes it.

Key Takeaways

  • A correlated subquery contains an outer reference and can return a different result for each outer row.
  • Qualifying columns prevents accidental references to the wrong query scope.
  • A scalar count can retain outer rows with no matches and return zero for them.
  • Comparing with a group maximum returns all tied rows.

EXISTS asks whether a query returns any row. It is true for one or more rows and false for none; it never produces unknown. Use a relationship inside the query to make the test about the current outer row.

Keep customers with matching orders
SELECT c.name
FROM customers c
WHERE EXISTS (
  SELECT 1 FROM orders o
  WHERE o.customer_id = c.customer_id
);

For Ana the inner query finds three orders, so she qualifies once. For Dara it finds none, so she is excluded. The result is Ana, Ben, and Chen. This kind of filtering is a semi-join: matching inner rows decide whether an outer row stays, without copying it once per match. SELECT 1 makes the intent clear; ordinary existence tests use the presence of rows, not their selected values.

Add order conditions inside the same subquery. Requiring o.amount > 50 returns Ben through his order for 64.00. Removing the customer link instead makes the test global: EXISTS (SELECT 1 FROM orders) is true for every customer whenever orders is nonempty.

Keep rows with no match

Replace EXISTS with NOT EXISTS to find Dara and Eli. This anti-join asks whether the related result is empty. It also works when a compared inner column contains nulls: null equality does not create a matching row.

For employees who manage nobody, link a potential report's manager to the outer employee:

SELECT e.name
FROM employees e
WHERE NOT EXISTS (
  SELECT 1 FROM employees r
  WHERE r.manager_id = e.employee_id
);

Lena, Sofia, and Tom qualify. Maya's null manager ID does not prevent this absence test from succeeding for them, as it would with a scalar NOT IN list containing NULL.

Turn "every" into "no missing requirement"

Suppose required(course) contains DB101 and STAT110. Ana completed both, Ben only DB101, Chen both plus ART100, and Dara none. The students(student) table lists all four.

SELECT s.student
FROM students s
WHERE NOT EXISTS (
  SELECT 1 FROM required r
  WHERE NOT EXISTS (
    SELECT 1 FROM completed c
    WHERE c.student = s.student
      AND c.course = r.course
  )
);

The deepest query looks for one student's completion of one required course. The middle query finds requirements that student lacks. The outer test keeps the student only when there are no missing requirements. Ana and Chen qualify; an extra course does not hurt Chen. This is relational division.

The missing list can also be built by subtracting completions:

WHERE NOT EXISTS (
  SELECT course FROM required
  EXCEPT
  SELECT course FROM completed c
  WHERE c.student = s.student
)

Both forms keep every student if required is empty, including Dara: there is no unmet requirement.

A counting form needs a unique, non-null required-course list and non-null course keys. The join excludes extra courses; distinct counting excludes repeated completion records:

SELECT c.student
FROM completed c
JOIN required r ON r.course = c.course
GROUP BY c.student
HAVING COUNT(DISTINCT c.course) = (SELECT COUNT(*) FROM required);

With an empty required list this grouped form has no groups and returns nobody, unlike the absence-based forms.

Key Takeaways

  • EXISTS tests for rows; ordinary SELECT 1 existence tests ignore selected values.
  • Keep the outer-to-inner link inside a correlated existence test.
  • NOT EXISTS expresses the absence of a matching row without the NOT IN null trap.
  • "Every requirement" can be tested as "no requirement is missing."
  • An empty required list makes the absence-based division tests true for every candidate.
  • The grouped counting form needs a nonempty, unique required list and matching course counts.

2.3 Choose between a join and a subquery

Choose a query form by the rows and columns the answer needs. A join pairs records; a membership or existence test decides whether to keep an outer record. An aggregate subquery supplies a comparison value.

Match the form to the output
NeedUseful form
Customer name beside each order amountJoin customers to orders
Customers who have an orderIN or correlated EXISTS
Customers without an orderCorrelated NOT EXISTS
Products above their category averageCorrelated scalar query or join to grouped values

An existence test keeps each qualifying outer row once. A join keeps one result for every matching pair. Ana has three orders, so an ordinary customer-order join returns her three times.

Rewrite membership without losing identities
SELECT DISTINCT c.customer_id, c.name
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id;

This returns Ana, Ben, and Chen once each, like membership filtering. The primary key in the selected columns matters: two customers can share a name. DISTINCT c.name would combine their identities, while DISTINCT c.customer_id, c.name preserves them.

Rewrite an absence test
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;

The left join preserves every customer. A customer with no orders has nulls in the order columns, so the final test keeps Dara and Eli. Test a right-side column that cannot be null in a real match, such as order_id. A nullable notes column could also be null on a genuine order and would give a false absence result.

The location of the null test matters. If o.order_id IS NULL is moved into ON, no real order satisfies the join condition. The left join then produces an unmatched row for every customer. All five customers return, including those with orders.

Rewrite a group comparison

A grouped derived table supplies each category's average as a column:

SELECT p.name, a.avg_price
FROM products p
JOIN (
  SELECT category, AVG(price) AS avg_price
  FROM products
  GROUP BY category
) a ON a.category = p.category
WHERE p.price > a.avg_price;

Stationery averages 5.00, home 16.50, and bags 26.00. Pen set, Desk lamp, and Backpack qualify, just as in the correlated query. The grouped result has one row per category, so each product can match at most one average. The join also makes that average available in the output.

Check a rewrite where it can fail

Use cases that expose changes in meaning: a customer with no orders, one with several orders, two customers sharing a name, a nullable right-side field, and a tied maximum. Compare row identities and duplicate counts as well as displayed values. Equivalent forms should agree on those cases. Their speed depends on the system and data; syntax alone does not establish which runs faster.

Key Takeaways

  • Use joins for matching pairs and existence tests for filtering outer rows.
  • Include entity keys when DISTINCT must preserve different people with the same name.
  • In a left-join absence test, put IS NULL in WHERE and test a column that is non-null on matches.
  • A join to one aggregate row per group can replace a correlated group comparison.
  • Check duplicate counts, missing matches, nulls, and ties when rewriting.
3

Combine result sets with set operations

Similar lists can be combined without pairing their rows. Set operations let you stack lists, keep their shared rows, or find what one list has and another lacks. The selected columns define what counts as a match, so adding a date or a source label changes the comparison. Work through duplicate counts and NULLs before combining several operators; the database's evaluation order can affect the final result.

3.1 Stack results with UNION and UNION ALL

A set operation combines query results by adding or comparing whole rows. UNION stacks two results and removes duplicate rows; UNION ALL stacks them and keeps every occurrence.

Combine the shop's city lists

Customers live in Lisbon, Toronto, Singapore, Lisbon, and Nairobi. stores(city) contains Lisbon, Toronto, and Berlin.

SELECT city FROM customers
UNION
SELECT city FROM stores
ORDER BY city;

The result has Berlin, Lisbon, Nairobi, Singapore, and Toronto: five distinct rows. Duplicate removal applies to the whole combined result, including the two Lisbon rows already present among customers. With UNION ALL, there are eight rows: Lisbon appears three times and Toronto twice.

Align columns by position

The two results must be union-compatible: the same column count, with compatible types in corresponding positions. Names do not determine matching. The output column names come from the first query.

SELECT name, city FROM customers
UNION ALL
SELECT name, city FROM suppliers;

Both branches put name first and city second. Reversing the supplier columns can still run because both are text, but supplier cities then appear under the output name column. Write the columns explicitly; SELECT * makes a later table change harder to spot. Type conversion also varies: PostgreSQL rejects combining an integer result with an incompatible text result, while SQLite accepts mixed types.

Sort the combined result

A final ORDER BY sorts the entire result and uses the first query's output names or column positions. A final row limit also applies to the combined result. An unwrapped ORDER BY between the first query and UNION is rejected by PostgreSQL, MySQL, SQL Server, and SQLite.

Neither form promises that rows arrive in branch order. Request the output order in the final query when it matters.

Label the origin of rows

A constant can show which list contributed a row:

SELECT name AS label, 'customer' AS source
FROM customers WHERE city = 'Lisbon'
UNION ALL
SELECT city, 'store'
FROM stores WHERE city = 'Lisbon';

The rows are Ana/customer, Dara/customer, and Lisbon/store. The column names are label and source, from the first branch. A source label becomes part of the row, so it also affects duplicate removal if UNION is used: identical names with different source values remain distinct rows.

Preserve meaningful repeats

Use UNION for a distinct list and UNION ALL when repeated rows matter or the inputs cannot overlap. Combining amounts from current and archived orders with UNION would merge equal amounts, even if they came from different orders. Two separate orders for 12.00 must contribute 24.00 to revenue; selecting only their amounts with UNION leaves one 12.00.

A join has a different purpose. It places related columns beside one another by matching rows, such as a customer name beside an order amount. A union places compatible rows into the same list. The duplicate policy should follow what one row means in that list.

Key Takeaways

  • UNION removes duplicate whole rows across both inputs; UNION ALL retains all occurrences.
  • Columns match by position and need compatible types; names come from the first query.
  • Write one final ORDER BY for the combined result.
  • Source labels participate in whole-row comparisons.
  • Keep meaningful repeats when combining amounts for later totals.

3.2 Find shared and missing rows with INTERSECT and EXCEPT

INTERSECT finds shared rows. EXCEPT finds rows in the first result that are missing from the second. Like UNION, both normally return distinct rows.

Read the direction of the comparison

With customer cities Lisbon, Toronto, Singapore, Lisbon, and Nairobi, and store cities Lisbon, Toronto, and Berlin:

OperationResult
Customers INTERSECT storesLisbon, Toronto
Customers EXCEPT storesNairobi, Singapore
Stores EXCEPT customersBerlin

Swapping the inputs leaves an intersection unchanged but reverses the question answered by a difference. MySQL supports these operators from 8.0.31. Oracle uses MINUS and also supports the name EXCEPT from 21c.

Select the columns that define a match

To find customers who ordered in March but not April:

SELECT customer_id FROM orders
WHERE order_date >= '2026-03-01'
  AND order_date < '2026-04-01'
EXCEPT
SELECT customer_id FROM orders
WHERE order_date >= '2026-04-01'
  AND order_date < '2026-05-01';

This returns Ben's ID 2 and Chen's ID 3. Ana ordered in both months. The half-open date ranges also work when the column includes times of day: the next month's boundary is excluded.

Adding order_date to each branch would compare customer-and-date pairs. A March pair can never equal an April pair, so that query would keep every distinct March pair, including Ana's. To display customer names, first calculate the missing IDs, then join those IDs to customers.

Compare duplicates and NULLs

Set comparisons treat two nulls in corresponding positions as matching. If both city lists have a null row, INTERSECT returns one null row and EXCEPT removes it. Ordinary NULL = NULL in WHERE is unknown; this is a different comparison rule.

The ALL forms retain multiplicities. A row appearing m times on the left and n times on the right appears the smaller of m and n times in INTERSECT ALL. In EXCEPT ALL, its count is m minus n, with zero as the minimum. Lisbon occurs twice among customers and once among stores, so EXCEPT ALL retains one Lisbon. The ordinary difference retains none. PostgreSQL, MySQL 8.0.31+, and Oracle 21c support these ALL forms; SQL Server and SQLite do not.

Control mixed-operation order

PostgreSQL, MySQL, and SQL Server give INTERSECT higher precedence than UNION and EXCEPT; the latter run left to right. SQLite and Oracle 21c evaluate the set operators left to right at equal precedence.

For lists A = {1, 2}, B = {2, 3}, C = {3}, A UNION B INTERSECT C means A union (B intersect C) in PostgreSQL, giving {1, 2, 3}. SQLite evaluates (A union B) intersect C, giving {3}. Define an intermediate CTE or derived table to make the intended grouping explicit. Parentheses also work where supported; SQLite does not accept them around individual compound-query branches.

NOT EXISTS offers another absence test when the outer row's full details or duplicate occurrences must remain. EXCEPT returns the selected common columns as a distinct list and matches nulls. An equality-based NOT EXISTS filter preserves qualifying outer rows and does not match two null keys.

Key Takeaways

  • INTERSECT keeps shared rows; EXCEPT subtracts right-side rows from the left.
  • Every selected column participates in row matching.
  • Set-operation duplicate checks treat corresponding nulls as equal.
  • INTERSECT ALL keeps the smaller count; EXCEPT ALL keeps the nonnegative count difference.
  • Mixed set operations need explicit grouping when dialect precedence differs.
  • EXCEPT and equality-based NOT EXISTS differ in duplicate and null handling.
4

Organize queries with common table expressions

Long SQL becomes easier to follow when each intermediate result has a name and a clear row meaning. Common table expressions put those steps before the final query, so a calculation can build on an earlier calculation without repeating its text. Use them to turn a question into a sequence of small results, check each step, and make the population behind an average or percentage explicit before combining the steps.

4.1 Define and chain CTEs

A common table expression, or CTE, names a query result for one statement. Define it with WITH, then read it like a table in the statement that follows.

Give an intermediate result a name
WITH customer_totals AS (
  SELECT customer_id, SUM(amount) AS total
  FROM orders
  GROUP BY customer_id
)
SELECT customer_id, total
FROM customer_totals
WHERE total > 50;

customer_totals has one row per customer with orders: 1/85.00, 2/76.00, and 3/8.00. The final filter keeps customers 1 and 2. The CTE does the same logical job as a derived table, but its definition appears before the query that reads it.

The parentheses enclose its query. There is no semicolon between the CTE definition and the final SELECT; together they form one statement. An optional column list can name its output: WITH customer_totals(customer_id, total) AS (...). For a complete, portable column list, supply one name per returned column.

Chain and reuse steps

Several CTEs share one WITH and are separated by commas:

WITH customer_totals AS (
  SELECT customer_id, SUM(amount) AS total
  FROM orders GROUP BY customer_id
), average_total AS (
  SELECT AVG(total) AS avg_total
  FROM customer_totals
)
SELECT customer_id, total
FROM customer_totals
WHERE total > (SELECT avg_total FROM average_total);

The second CTE reads the first. The main query reads the totals again, without repeating their definition. Define each CTE before those that depend on it for portability. SQLite and PostgreSQL with WITH RECURSIVE allow some forward references, but that is unnecessary here. Repeating WITH before the second definition or leaving a comma before the main query breaks this structure.

Know how long the name lasts
ObjectWhat it provides
CTEA named result within one statement
ViewA query definition stored in the database schema
Temporary tableStored rows with a lifetime set by the system and creation options

A later statement cannot read the earlier statement's customer_totals. A CTE's name is available within its statement, not for the rest of a session.

Place ordering and changes deliberately

The final ORDER BY controls the displayed row order. Ordering a CTE's internal query does not promise the final order. SQL Server restricts ORDER BY inside a CTE unless used with TOP or OFFSET. In SQL Server, terminate the preceding statement with a semicolon; scripts often use ;WITH to ensure that boundary. MySQL supports CTEs from version 8.0.

PostgreSQL, MySQL, and SQL Server also permit WITH before UPDATE and DELETE. For example, in PostgreSQL:

WITH inactive AS (
  SELECT c.customer_id FROM customers c
  WHERE NOT EXISTS (
    SELECT 1 FROM orders o
    WHERE o.customer_id = c.customer_id
  )
)
DELETE FROM customers
WHERE customer_id IN (SELECT customer_id FROM inactive);

This would delete Dara and Eli. Before running a data-changing statement, preview the affected rows by using the same CTE with a final SELECT in place of the change.

Key Takeaways

  • A CTE names a result for the single statement that follows its WITH clause.
  • Separate multiple CTEs with commas and define dependencies first.
  • Reuse a CTE name wherever its result is needed in the statement.
  • Only the final query establishes the displayed sort order.

4.2 Solve a multi-step question in named steps

Multi-step questions become easier to write when the meaning of each intermediate row is settled first. "One row per order" and "one row per customer" are different inputs to an average.

Plan the rows before the SQL

For "Which customers spent more than the average customer, and by how much?", define the population as customers with orders. The result needs each qualifying customer's name, total, and difference from the average total.

  1. Build one total per customer with orders.
  2. Average those totals to get one comparison row.
  3. Compare each total with that average and attach the customer's name.
WITH customer_totals AS (
  SELECT customer_id, SUM(amount) AS total
  FROM orders GROUP BY customer_id
), average_total AS (
  SELECT AVG(total) AS avg_total
  FROM customer_totals
)
SELECT c.name, t.total,
       t.total - a.avg_total AS above_avg
FROM customer_totals t
JOIN average_total a ON t.total > a.avg_total
JOIN customers c ON c.customer_id = t.customer_id;

Run the first CTE with SELECT * FROM customer_totals: it should have three rows, with totals 85.00, 76.00, and 8.00. Then check average_total: their sum is 169.00 and their mean is about 56.33. Finally compare the totals. Ana is about 28.67 above average and Ben about 19.67 above; Chen is excluded. Keep full precision in the query and round the displayed answer at the end.

Include zero-spend customers when the question needs them

"Average customer" may instead mean all five customers. Build that population explicitly:

SELECT c.customer_id, COALESCE(SUM(o.amount), 0) AS total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id;

Now Dara and Eli contribute 0.00. The mean is 169.00 divided by 5, or 33.80. Ana and Ben still qualify, but their differences change to 51.20 and 42.20. Changing only the final label cannot change an average's denominator; the input rows must represent the intended population.

Build a share from compatible steps

A grand_total CTE can hold SUM(total) from the customer totals. The main query computes 100.0 * t.total / g.total_revenue, joining that single grand-total row to each customer row. The shares, rounded to one decimal, are Ana 50.3%, Ben 45.0%, and Chen 4.7%.

After defining customer_totals, append this CTE and final query:

, grand_total AS (
  SELECT SUM(total) AS total_revenue FROM customer_totals
)
SELECT t.customer_id, 100.0 * t.total / g.total_revenue AS pct
FROM customer_totals t
CROSS JOIN grand_total g;

Multiplying by 100.0 before division gives a decimal calculation. With integer operands, PostgreSQL, SQL Server, and SQLite discard the fraction in integer division; 85 / 169 becomes 0. Multiplying that zero afterward cannot recover the lost fraction. A share also needs a nonzero denominator; decide what a zero-revenue report should display.

Find the first step that changes the row meaning

Check every intermediate result's columns, row count, and totals. If a join attaches all six orders to the three customer totals without the customer link, it creates 18 rows and repeats the totals. Fix that join before aggregating again.

CTEs can contain subqueries, joins, and set operations. Naming March customer IDs and April customer IDs lets the main query subtract one list from the other with EXCEPT. The names clarify the steps; the selected columns still determine whether the comparison is between customers or between customer-and-date pairs.

Key Takeaways

  • Define the final rows and each intermediate row meaning before writing the steps.
  • Check every named result independently before combining it.
  • An average over all customers needs zero rows for customers without orders.
  • Use decimal arithmetic before division to preserve fractional shares.
  • Unexpected row multiplication points to a join that changes the intended row meaning.
5

Query hierarchies with recursive CTEs

A hierarchy has no fixed number of levels, and a network may revisit a place it has already reached. Recursive CTEs handle both by starting with an anchor and repeatedly producing the next rows. Trace that process first with numbers, then with employees and parts. The join direction, carried columns, duplicate policy, and stopping rule together determine whether the result is a useful traversal or an endless sequence.

5.1 Build a recursive CTE

A recursive CTE builds a result by using newly reached rows to find more rows. Its anchor member supplies the starting rows; its recursive member supplies the next step.

Trace a small sequence
WITH RECURSIVE n(k) AS (
  SELECT 1
  UNION ALL
  SELECT k + 1 FROM n WHERE k < 5
)
SELECT k FROM n
ORDER BY k;

The anchor produces 1. The recursive member reads that step's row and produces 2. The next step produces 3, followed by 4 and 5. When the input row is 5, k < 5 is false and no next row is produced. The final result combines all five steps.

Think of each step as a frontier of newly produced rows. The recursive reference supplies that frontier, not the entire accumulated result. The database can implement this process differently; SQLite, for example, uses a queue. The stopping behavior follows the same rule: no new rows means no further expansion.

The condition tests the input row. Replacing < 5 with <= 5 allows the input 5 to produce 6, creating an off-by-one error. Starting at 1 and ending at 100 gives a final SUM(k) of 5050.

Generate dates to show missing days

An orders-only GROUP BY cannot show a day with no orders. Generate all seven dates first, then left join the orders. In SQLite:

WITH RECURSIVE days(d) AS (
  SELECT '2026-03-01'
  UNION ALL
  SELECT date(d, '+1 day') FROM days
  WHERE d < '2026-03-07'
)
SELECT d, COUNT(o.order_id) AS order_count,
       COALESCE(SUM(o.amount), 0) AS total
FROM days
LEFT JOIN orders o ON o.order_date = d
GROUP BY d
ORDER BY d;

March 2 has one order totaling 30.00 and March 5 one totaling 12.00. The other five days show count 0 and total 0. Date arithmetic changes by system: PostgreSQL adds 1 to a DATE, SQL Server uses DATEADD(day, 1, d), and MySQL uses d + INTERVAL 1 DAY.

Adjust the recursive syntax

PostgreSQL and MySQL require WITH RECURSIVE; SQLite accepts that spelling too. SQL Server and Oracle use WITH without RECURSIVE. Oracle requires the CTE column list. SQL Server and Oracle require UNION ALL between the anchor and recursive member; PostgreSQL, MySQL, and SQLite also permit UNION.

Reference the recursive CTE once in its recursive member. PostgreSQL, MySQL, SQL Server, and SQLite reject SUM and COUNT there; put final aggregation after the traversal. MySQL and SQL Server also reject recursive GROUP BY and DISTINCT.

Make growing columns fit

Both members need compatible column types. A path that grows beyond a narrow anchor string can fail. PostgreSQL can use CAST(name AS TEXT) in the anchor to match text concatenation. In MySQL use CAST(name AS CHAR(1000)); a narrow type can truncate or raise an error. In SQL Server cast both anchor and recursive path expressions to the same type and length, such as VARCHAR(1000). The chosen width must fit the paths being built.

Key Takeaways

  • The anchor supplies starting rows; the recursive member produces the next rows.
  • Recursion stops when no further rows are produced.
  • A stopping condition tests the previous step, so check its boundary carefully.
  • A generated date series supplies rows for days with no events.
  • Aggregate after the recursive traversal and keep growing column types compatible.

5.2 Walk trees and graphs with recursion

An adjacency list stores each item's parent key in its row. Recursion follows that link repeatedly, so the query can handle a hierarchy without knowing its depth in advance.

Walk down from a manager

The employee hierarchy is Maya → Omar and Lena; Omar → Raj and Sofia; Raj → Tom. Omar's employee ID is 2. Start with his direct reports, then find each report's reports:

WITH RECURSIVE reports(employee_id, name, depth) AS (
  SELECT employee_id, name, 1
  FROM employees WHERE manager_id = 2
  UNION ALL
  SELECT e.employee_id, e.name, r.depth + 1
  FROM employees e
  JOIN reports r ON e.manager_id = r.employee_id
)
SELECT name, depth FROM reports
ORDER BY depth, name;

The anchor produces Raj and Sofia at depth 1. Raj leads to Tom at depth 2; Sofia leads to nobody. Tom has no reports, so expansion ends. Omar himself is excluded because the anchor starts with his reports.

Reverse the direction to find ancestors

To find Tom's managers, start with Tom at depth 0 and carry manager_id. The recursive join becomes e.employee_id = up.manager_id: look up the employee whose ID is the current row's manager ID. This reaches Raj at depth 1, Omar at 2, and Maya at 3. Maya's null manager ID matches no next row. Use WHERE depth > 0 in the final query to exclude Tom from his own manager list.

The complete upward query carries the manager key needed by the next step:

WITH RECURSIVE up(employee_id, name, manager_id, depth) AS (
  SELECT employee_id, name, manager_id, 0
  FROM employees WHERE name = 'Tom'
  UNION ALL
  SELECT e.employee_id, e.name, e.manager_id, up.depth + 1
  FROM employees e
  JOIN up ON e.employee_id = up.manager_id
)
SELECT name, depth FROM up
WHERE depth > 0
ORDER BY depth;

A depth cap belongs in the recursive member when it must stop expansion. In the downward query, WHERE r.depth < 2 permits depth-1 rows to produce depth-2 rows, then stops. A final WHERE depth <= 2 only filters what is displayed after expansion.

Carry a path for display

A root-to-employee path starts with Maya's name and extends with r.path || ' > ' || e.name. It can produce "Maya > Omar > Raj > Tom". Sort the final result by the path to place a manager before descendants, with siblings ordered by name. Depth can supply indentation. In MySQL use CONCAT(r.path, ' > ', e.name); SQL Server uses + or CONCAT. Give the growing path a suitable type in both members.

Decide whether repeated routes matter

A graph can reach one item through several parents. DB401 requires DB301 and DB201; DB301 requires DB201 and STAT110; DB201 requires DB101. Starting with DB401's direct requirements, UNION ALL reaches six rows: DB301, DB201, another DB201, STAT110, and two DB101 rows. For a distinct list of prerequisites, deduplicate the course-only result with recursive UNION where supported, or SELECT DISTINCT after a terminating traversal. The four courses are DB101, DB201, DB301, and STAT110.

In a parts list, separate routes can represent separate requirements. A bicycle needs two wheels and one frame; each wheel needs 32 spokes and one rim. Carry quantity by multiplying along each path: b.total_qty * p.qty. The result includes 64 spokes and two rims. Keep routes with UNION ALL, then SUM(total_qty) GROUP BY component at the end. If two subassemblies each need four identical bolts, merging their identical (bolt, 4) rows would lose half the required bolts.

Key Takeaways

  • The recursive join direction determines whether a traversal finds children or parents.
  • Depth records distance from the anchor; choosing the anchor decides whether the starting item appears.
  • Apply a recursive depth condition to stop expansion, not just hide deeper output.
  • A graph can reach the same item through more than one path.
  • Multiply quantities along a parts path and sum contributions after traversal.
  • Keep meaningful repeated paths with UNION ALL.

5.3 Prevent infinite recursion and handle cycles

A cycle returns a traversal to a node already reached on its route. Networks can contain cycles naturally; an employee hierarchy can contain one through a mistaken manager link. A recursive query needs a termination rule that fits its data and output columns.

Inspect the whole recursive row

For routes A → B, B → C, and C → A, UNION ALL repeatedly produces A, B, C, A, B, C. Adding a changing hop count gives a new row every time.

Recursive UNION removes rows already produced. With only a city column, A, B, and C are each retained once; the next A is discarded and no frontier remains. With (city, hops), (A, 0) and (A, 3) differ, so deduplication does not stop the cycle. A changing path has the same problem.

Block revisits on the current path

For one-letter city codes A, B, and C, this SQLite/PostgreSQL text-path form keeps a route from revisiting a city:

WITH RECURSIVE trip(city, path, hops) AS (
  SELECT 'A', ',A,', 0
  UNION ALL
  SELECT r.to_city, t.path || r.to_city || ',', t.hops + 1
  FROM trip t
  JOIN routes r ON r.from_city = t.city
  WHERE t.path NOT LIKE '%,' || r.to_city || ',%'
)
SELECT city, path, hops FROM trip;

It produces A/",A,"/0, B/",A,B,"/1, and C/",A,B,C,"/2. The next step would revisit A, which is already in the path, so it is blocked. Delimiters prevent partial-token matches. For this text technique, use tokens without commas or LIKE wildcards % and _; arbitrary names need escaping or a structured representation. PostgreSQL arrays provide such a representation. MySQL uses CONCAT for both path extension and pattern construction.

Path tracking is local to each route. Two different routes may still reach the same destination, so use a final DISTINCT city when the answer needs only distinct destinations.

Separate cycle prevention from a depth cap

An anchor at hop 0 with WHERE hops < 5 permits hops 0 through 5. On this cycle it returns A, B, C, A, B, C: six rows. It terminates, but retains revisits. That is useful for bounded reachability, followed by distinct destinations if needed. Filtering hops <= 5 only in the final query would not stop unlimited expansion.

SQL Server's default recursive limit is 100 levels. A final OPTION (MAXRECURSION n) changes it; 0 disables the limit and values up to 32767 set a cap. MySQL's cte_max_recursion_depth defaults to 1000. PostgreSQL and SQLite have no default recursion-depth cap for these CTEs. Limits are a backup; hitting one can abort an otherwise incorrect query.

PostgreSQL 14+ supports the standard CYCLE clause, such as CYCLE city SET is_cycle USING path. It marks a cycle-closing row and prevents further extension from it. MySQL, SQL Server, and SQLite lack that clause.

Check that the next row really advances

Even acyclic data can loop if the recursive member selects r.employee_id, r.name from its own current row after joining to children. A manager with a child then reproduces itself forever under UNION ALL. Select e.employee_id, e.name from the newly matched employee instead.

Key Takeaways

  • UNION stops a cycle only when the complete recursive rows repeat.
  • A path test blocks a destination already visited on that path.
  • A depth cap limits expansion but can still include revisits.
  • Database recursion limits are a backup, not a replacement for correct termination.
  • The recursive member must return newly reached rows instead of reproducing its input.
  • PostgreSQL CYCLE marks cycle-closing rows and stops expanding them.

SQL Subqueries and CTEs examples

5 Walkthroughs

1

Build an answer from an inner result

14 steps
Work through scalar values, derived tables, membership, and the effect of empty or nullable lists.
  1. 1
    IntroductionChoose the result shape first

    A nested query puts one SQL result inside another statement. The useful question is: what does the outer query need here—a single value, a list of values, or a table of intermediate rows?

    Start with product prices, then move to grouped order counts and list comparisons. At each step, work out the inner result before deciding what the outer query will keep. A query that runs can still have the wrong result shape.

  2. 2
    ExampleCreate the comparison value

    The product prices are 4.00, 6.00, 25.00, 8.00, 40.00, and 12.00. Their total is 95.00, so their average is about 15.83.

    SELECT AVG(price) FROM products;
    

    This inner query produces one row and one column. That makes it suitable as a scalar value in an outer comparison. Keep the computed precision; the rounded 15.83 is for displaying the result.

  3. 3
    ExampleUse that value for each product

    Now place the average where the outer query needs one comparison value:

    SELECT name, price FROM products
    WHERE price > (SELECT AVG(price) FROM products);
    

    Desk lamp at 25.00 and Backpack at 40.00 qualify. The outer WHERE tests individual rows, while the inner query has its own aggregation level. Writing AVG directly in the same WHERE would not create that separate level.

  4. 4
    ChallengePredict the empty scalar result

    A catalog query compares each price with (SELECT price FROM products WHERE name = 'Missing item'). No product has that name. Will the comparison keep any rows?

    ---reveal---

    No. A scalar query with no rows contributes NULL, and an ordinary price comparison with NULL is unknown. WHERE keeps only true conditions. This is different from an empty COUNT aggregate, which still returns one row containing 0.

  5. 5
    ExampleCount before averaging

    Ana has three orders, Ben two, and Chen one. First turn those six order rows into three count rows:

    SELECT customer_id, COUNT(*) AS order_count
    FROM orders GROUP BY customer_id;
    

    The result is customer 1/count 3, customer 2/count 2, and customer 3/count 1. One row now means one customer with orders. That is the input needed for an average of customer order counts.

  6. 6
    ExampleRead the grouped result as a table

    Wrap the grouped query in FROM and name it:

    SELECT AVG(order_count)
    FROM (
      SELECT customer_id, COUNT(*) AS order_count
      FROM orders GROUP BY customer_id
    ) per_customer;
    

    The outer query averages 3, 2, and 1, giving 2.0. The name order_count belongs to the inner result's column, so the outer aggregate can read it. Two query levels express the two aggregation stages.

  7. 7
    ChallengeCheck which customers were counted

    The same shop has five customers, but Dara and Eli have no orders. Does the average of 2.0 describe all five customers? What average would include their zero counts?

    ---reveal---

    No. The orders-only result contains only three customers. All five counts are 3, 2, 1, 0, and 0, giving 1.2. Start from customers, left join orders, and count the non-null order key to create those missing zero rows.

  8. 8
    ConnectionRecover details without losing ties

    A grouped maximum date gives one date per customer but does not identify an arbitrary single order. Join that result back to orders on both customer ID and date.

    For the shop, the latest order IDs are 106, 105, and 104. If a customer has two orders on that customer's latest date, both match. The grouped result supplies the maximum value; the join retrieves all detail rows with that value.

  9. 9
    ExplanationTest membership without repeating rows

    The order customer IDs are 1, 2, 1, 3, 2, 1. A membership query asks whether each customer's ID occurs in that list:

    SELECT name FROM customers
    WHERE customer_id IN (
      SELECT customer_id FROM orders
    );
    

    Ana, Ben, and Chen each return once. The repeated inner IDs do not multiply them. A join to orders would instead return one row for each customer-order pair.

  10. 10
    ExampleTrace one NOT IN comparison

    A manager-ID list contains NULL, 1, 1, 2, 2, and 4. For employee ID 3, NOT IN requires inequality to every listed value.

    The inequalities with 1, 2, and 4 are true. The inequality with NULL is unknown, so the full test cannot be true. Matching manager IDs fail as well. The filter returns nobody, even though some employees manage no one. Remove inner nulls or use a correlated NOT EXISTS absence test.

  11. 11
    Key InsightSeparate ANY from ALL

    With the comparison list 4.00 and 6.00, a price of 6.00 is greater than at least one value but is not greater than both.

    • 6 > ANY (...) is true through the 4.00 comparison.
    • 6 > ALL (...) is false through the 6.00 comparison.

    SOME is a synonym for ANY. Not-equal-to ANY also needs just one success, so it cannot stand in for NOT IN: a value may differ from one list entry while matching another.

  12. 12
    ChallengeTry an empty category

    There are no garden products. Compare a filter using price > ALL (SELECT price FROM products WHERE category = 'garden') with one using price > (SELECT MAX(price) FROM products WHERE category = 'garden'). Which keeps the six non-null product prices?

    ---reveal---

    ALL keeps all six because the list is empty. MAX returns NULL, so its ordinary comparison keeps none. A maximum-based rewrite changes the empty-input behavior.

  13. 13
    ChallengeRepair a multi-step filter

    A report needs products above every reference price, including the case of an empty reference list. It also needs to reject the comparison if any reference price is unknown. Can a scalar MAX subquery meet both requirements unchanged?

    ---reveal---

    No. MAX returns NULL for an empty list and ignores NULL entries in a nonempty list. ALL has the required filter behavior. In PostgreSQL, NOT EXISTS of a comparison that IS NOT TRUE can express the same row selection.

  14. 14
    RecapRead shapes and edge cases together

    A scalar query supplies a value; a derived table supplies rows for another query level; a membership query supplies a list. Those shapes explain why some expressions need a wrapper and why a repeated list entry does not duplicate an outer row.

    When checking an answer, include zero rows, several rows, and NULL values. Empty-list ALL and an empty MAX aggregate behave differently, so a shorter-looking rewrite can change which rows qualify.

2

Follow each outer row to its related rows

15 steps
Compare within groups, find matches and missing requirements, then audit join rewrites.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake the relationship visible
  2. 2
    ExampleGive the product two roles
  3. 3
    ExampleTrace the category comparisons
  4. 4
    ChallengeSpot the missing owner
  5. 5
    TipKeep zero counts and tied maxima
  6. 6
    ExplanationTurn a match into a yes-or-no test
  7. 7
    ExampleFind customers without orders
  8. 8
    ChallengeCheck where the condition belongs
  9. 9
    ExampleBuild the missing-course list
  10. 10
    Key InsightExpress every as no missing item
  11. 11
    ChallengeRemove every requirement
  12. 12
    ConnectionRewrite while keeping identities
  13. 13
    ChallengeAudit a tempting left-join rewrite
  14. 14
    ChallengeCombine a group comparison with details
  15. 15
    RecapCheck links and row counts
3

Combine lists without losing their meaning

11 steps
Track whole rows, duplicate counts, and set-operation grouping across related lists.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionChoose what one row means
  2. 2
    ExampleStack the two city lists
  3. 3
    TipAlign positions and sort once
  4. 4
    ChallengePreserve separate revenue events
  5. 5
    ExampleFind shared or missing cities
  6. 6
    ExampleCompare customer IDs across periods
  7. 7
    ExplanationCount repeated rows deliberately
  8. 8
    ChallengeCompare a null city
  9. 9
    Key InsightMake grouping visible
  10. 10
    ChallengeKeep events, then compare keys
  11. 11
    RecapMatch rows before choosing operators
4

Turn a report into named SQL steps

11 steps
Build customer totals, define the population, and verify an average and revenue-share report.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionGive each intermediate result a job
  2. 2
    ExampleDefine customer totals once
  3. 3
    ExampleAdd a dependent step
  4. 4
    ChallengeTry to reuse the name later
  5. 5
    ExampleCompare totals with the average
  6. 6
    Key InsightChange the population in the totals
  7. 7
    ChallengePredict a changed difference
  8. 8
    ExampleCompute a revenue share
  9. 9
    TipFind where rows multiply
  10. 10
    ChallengeAudit a complete reporting plan
  11. 11
    RecapVerify each named result
5

Trace recursion through numbers, trees, and cycles

18 steps
Build a recursive sequence, walk a hierarchy, preserve parts contributions, and stop graph cycles.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow the next frontier
  2. 2
    ExampleWrite an anchor and one recursive step
  3. 3
    ExampleTrace the boundary row
  4. 4
    ChallengeChoose the condition for an endpoint
  5. 5
    ConnectionUse dates to supply missing report rows
  6. 6
    ExampleAnchor the direct reports
  7. 7
    ExampleJoin to the next employees
  8. 8
    ChallengeWalk in the opposite direction
  9. 9
    TipCarry a path that can grow
  10. 10
    ExampleKeep quantities from different routes
  11. 11
    ChallengeChoose whether a repeated destination matters
  12. 12
    ExplanationSee why a hop count defeats deduplication
  13. 13
    ExampleBlock a city already on the path
  14. 14
    ChallengeDistinguish depth caps from visited checks
  15. 15
    TipUse system guards as a backup
  16. 16
    ChallengeAdvance the selected row as well as the join
  17. 17
    ChallengeCombine output needs with termination
  18. 18
    RecapAudit the whole recursive row

SQL Subqueries and CTEs practice questions

40 Practice Questions in 4 sets

Set 1: Read results and choose the right query shape10 Practice Questions

Question 1 of 10

A PostgreSQL scalar subquery is used in price = (SELECT price FROM offers WHERE item_id = 17). That inner query returns two rows, both containing 9.00. What happens?
  1. The comparison uses 9.00 because both values agree.
  2. The statement fails because two rows were returned.
  3. The outer row is returned twice, once per offer.
  4. The comparison gives NULL because the values repeat.
Show answerHide answer
Answer: B
A scalar subquery may return at most one row, even when several rows contain identical values. PostgreSQL raises a cardinality error here. Equal values do not automatically become one row; a deliberate aggregate or a query guaranteed to return one row is needed when one value is intended.

Question 2 of 10

A library has four members. Loan counts are 4, 2, 0, and 0. What does this query return?

SELECT AVG(loan_count)
FROM (SELECT member_id, COUNT(*) AS loan_count
      FROM loans GROUP BY member_id) counts;
  1. 1.5, because all four members share six loans.
  2. 2.0, because the two zero counts form one group.
  3. 6.0, because the outer query totals all loan counts.
  4. 3.0, because only members with loans form groups.
Show answerHide answer
Answer: D
The inner query starts from loans, so it produces only the two members who have loans, with counts 4 and 2. Their average is 3.0. Dividing the six loans by all four members would give 1.5, but the query never creates rows for the members with zero loans.

Question 3 of 10

blocked(code) contains the rows 7 and NULL. A filter tests code NOT IN (SELECT code FROM blocked) for non-null codes 7, 8, and 9. Which codes pass?
  1. No codes pass.
  2. Only 8 and 9 pass.
  3. Only code 7 passes.
  4. All three codes pass.
Show answerHide answer
Answer: A
Code 7 has a matching blocked value, so its test is false. For 8 and 9, comparison with 7 succeeds as an inequality but comparison with NULL is unknown; their full NOT IN tests are unknown and fail the filter. Treating the null as if it were absent would incorrectly keep 8 and 9.

Question 4 of 10

items(item_id, category, price) contains A/tools/10, B/tools/18, C/books/8, and D/books/12. What item IDs pass this filter?

WHERE i.price > (SELECT AVG(j.price) FROM items j
                 WHERE j.category = i.category)
  1. A and C
  2. B only
  3. B and D
  4. A and D
Show answerHide answer
Answer: C
The tool average is 14 and the book average is 10. B at 18 and D at 12 each exceed their own category average. Selecting B alone uses the overall average of 12 instead; the correlated category condition means D is compared with 10, and strict greater-than then keeps it.

Question 5 of 10

A museum has six visitors in visitors. bookings is nonempty but has rows for only two visitors. How many rows does this query return?

SELECT v.visitor_id FROM visitors v
WHERE EXISTS (SELECT 1 FROM bookings);
  1. 0 visitor rows
  2. 2 visitor rows
  3. The number of bookings
  4. 6 visitor rows
Show answerHide answer
Answer: D
The inner query contains no reference to the current visitor. Because bookings is nonempty, its existence test is true for every one of the six visitors. Returning only the two visitors with bookings would require a condition linking each booking to v.visitor_id inside the subquery.

Question 6 of 10

Two different accounts share the name "Lee" and both have transactions. An EXISTS query selects their account IDs and names. What preserves those identities when rewriting it as an inner join?
  1. Select DISTINCT a.name from the joined rows.
  2. Select DISTINCT a.account_id, a.name from the joined rows.
  3. Select a.account_id, a.name from every joined row.
  4. Select a.name from the joined rows and sort by ID.
Show answerHide answer
Answer: B
The join can create several rows per account, so distinct account-ID-and-name pairs restore one row per account. Including the ID keeps the two accounts separate even though their names agree. Distinct names alone would collapse both accounts into one displayed row and lose an identity the original query retained.

Question 7 of 10

The one-column results are east: 2, 2, 5 and west: 2, 8. How many rows does east UNION ALL west contain?
  1. 5 rows
  2. 3 rows
  3. 4 rows
  4. 2 rows
Show answerHide answer
Answer: A
UNION ALL retains every occurrence from both inputs, so three rows plus two rows gives five. The three occurrences of 2 remain separate rows. A result of three rows would be the distinct values 2, 5, and 8 from UNION, which applies a different duplicate policy.

Question 8 of 10

In PostgreSQL, a one-column result A contains 4, 4, 4, 9 and B contains 4, 4, 6. What is the multiset result of A EXCEPT ALL B?
  1. 9 only
  2. 4, 4, 9
  3. 4, 9
  4. 4, 6, 9
Show answerHide answer
Answer: C
Subtract the right-side occurrence count for each value from the left-side count, stopping at zero. Three copies of 4 minus two copies leaves one 4, and the unmatched 9 remains. Returning only 9 would apply distinct EXCEPT, which removes 4 entirely because it occurs on the right.

Question 9 of 10

A script defines WITH totals AS (...) SELECT * FROM totals; successfully. Its next statement is SELECT * FROM totals;, and no table or view named totals exists. Why does the second statement fail?
  1. The first SELECT consumed the stored totals rows.
  2. The CTE name was scoped to the first statement.
  3. The CTE can be read again only with DISTINCT.
  4. The first statement needed a final ORDER BY.
Show answerHide answer
Answer: B
A CTE name belongs to the single statement attached to its WITH clause. The semicolon ends that statement, so the next statement has no object named totals to read. The rows were not consumed by reading them; the name simply has no scope in that second statement.

Question 10 of 10

A PostgreSQL query starts with SELECT 2 and recursively runs SELECT k + 3 FROM seq WHERE k < 10 with UNION ALL. The main query is SELECT SUM(k) FROM seq WHERE k <= 10. What total is returned?
  1. 26
  2. 10
  3. 18
  4. 15
Show answerHide answer
Answer: D
The recursive rows are 2, 5, 8, and 11: the input 8 still passes the test and produces 11, which cannot expand further. The final filter removes 11, leaving a sum of 15, not 26. A final filter changes the visible result after expansion; it does not change the recursive stopping test.
Set 2: Follow matches, missing rows, and named steps10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

measurements(value) is empty. In PostgreSQL, what two values are returned by SELECT (SELECT COUNT(*) FROM measurements), (SELECT MAX(value) FROM measurements)?
  1. NULL, NULL
  2. 0, 0
  3. 0, NULL
  4. No result row
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

In PostgreSQL, benchmarks(y) contains 3 and NULL. Candidate values are 2, 6, and NULL. Compare filters x > ALL (SELECT y FROM benchmarks) and x > (SELECT MAX(y) FROM benchmarks). Which candidates does each keep?
  1. ALL: none; MAX: 6 only.
  2. ALL: 6 only; MAX: 6 only.
  3. ALL: none; MAX: none.
  4. ALL: 6 and NULL; MAX: 6 only.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

departments(dept_id) contains 10 and 20. equipment(item_id) contains three rows and has no dept_id. In PostgreSQL, what does this query return?

SELECT d.dept_id FROM departments d
WHERE d.dept_id IN (SELECT dept_id FROM equipment);
  1. An error because the inner column is missing.
  2. Only department 10, from the first equipment row.
  3. Neither department, because no equipment is linked.
  4. Both departments, through an outer reference.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

required(skill) holds SQL and modeling, with unique non-null keys. Inez has SQL, modeling, and testing; Ko has SQL only; Luz has modeling only. A query keeps candidates for whom no required skill is missing. Who qualifies?
  1. Inez and Ko
  2. Inez only
  3. Ko and Luz
  4. Nobody qualifies
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Two unrelated sales rows each contain an amount of 14.00, one in current sales and one in archived sales. A derived table selects only amount and combines the two tables with UNION, then the outer query sums amount. What is returned?
  1. 28.00
  2. 14.00
  3. 2.00
  4. NULL
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

In PostgreSQL, A contains NULL, NULL, and 7; B contains one NULL. Compare SELECT x FROM A EXCEPT SELECT x FROM B with SELECT a.x FROM A a WHERE NOT EXISTS (SELECT 1 FROM B b WHERE b.x = a.x). What do they return?
  1. EXCEPT: 7; NOT EXISTS: 7.
  2. EXCEPT: NULL, 7; NOT EXISTS: 7.
  3. EXCEPT: no rows; NOT EXISTS: 7.
  4. EXCEPT: 7; NOT EXISTS: NULL, NULL, 7.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

The CTE counts depends on raw_data. What is the portable structure for defining both in one statement?
  1. WITH counts AS (... raw_data ...), raw_data AS (...) SELECT ...
  2. WITH raw_data AS (...) WITH counts AS (... raw_data ...) SELECT ...
  3. WITH raw_data AS (...), counts AS (... raw_data ...) SELECT ...
  4. WITH raw_data AS (...); WITH counts AS (... raw_data ...) SELECT ...
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Five subscriptions have payment totals 90, 30, 0, 0, and 0. A CTE built only from payments groups by subscription and averages the resulting totals. What changes when it is rebuilt from all subscriptions with a left join and zero for missing totals?
  1. The average changes from 60 to 24.
  2. The average changes from 24 to 60.
  3. The average stays 60 because revenue is unchanged.
  4. The average becomes 0 because most totals are zero.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A kit needs two panels and three braces. Each panel needs four screws and each brace needs two screws. A recursive parts query carries component and path quantity, retaining every route. What final screw total should it report, and how should it combine contributions?
  1. 6 screws, using MAX over the two route quantities.
  2. 8 screws, using UNION to keep distinct contributions.
  3. 12 screws, using COUNT over the expanded component rows.
  4. 14 screws, using UNION ALL then SUM by component.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A recursive CTE on A → B → A uses UNION and carries (node, hops), increasing hops at each step. Why can it keep expanding?
  1. UNION compares only the first selected column.
  2. The changing hop count makes repeated visits different rows.
  3. UNION removes duplicates only from the anchor member.
  4. The final row order causes old nodes to be visited again.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Trace intermediate rows and boundary cases10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

allowed(code) is empty in PostgreSQL. The outer codes are 4 and NULL. Which rows pass code <> ALL (SELECT code FROM allowed)?
  1. Both outer rows
  2. Only code 4
  3. Only the null row
  4. Neither outer row
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A sensor has readings (sensor_id, reading_id, time) of (8, 21, 10:00), (8, 22, 12:00), and (8, 23, 12:00). A derived table finds the maximum time per sensor, then joins back on sensor ID and time. Which reading IDs return?
  1. 22 only
  2. 21, 22, and 23
  3. 23 only
  4. 22 and 23
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

bids(item_id, bidder, amount) has K/Ren/15, K/Sol/15, M/Tai/9, and M/Ren/3. A query first keeps bids equal to their own item's maximum, then excludes any bidder who has a bid below that bid's own item average. Which bid rows remain?
  1. K/Ren/15 and K/Sol/15
  2. K/Ren/15 and M/Tai/9
  3. K/Sol/15 and M/Tai/9
  4. K/Sol/15 and M/Ren/3
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Candidates are Nia, Oren, and Pia. The required-certification table is empty. Nia has one unrelated certification; the others have none. What do a double-NOT EXISTS division query and a counting query using an inner join to required certifications return?
  1. Both return all three candidates.
  2. Absence test: all three; grouped count: nobody.
  3. Absence test: Nia; grouped count: nobody.
  4. Absence test: nobody; grouped count: all three.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

PostgreSQL evaluates this expression from three one-column queries: A UNION B INTERSECT C EXCEPT D. Their distinct values are A = {1, 4}, B = {2, 4}, C = {2}, and D = {4}. What is the result?
  1. {2}
  2. {1, 4}
  3. {1, 2, 4}
  4. {1, 2}
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

WITH points(a, b, c, d) AS (SELECT player_id, score, round_id FROM results) SELECT * FROM points is run in PostgreSQL. Why is this CTE definition invalid?
  1. The explicit column list has more names than returned columns.
  2. The CTE query must select from another CTE instead of a table.
  3. The main query must repeat the explicit column list in SELECT.
  4. The CTE query cannot use column names without table aliases.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A SQLite CTE contains integer part = 7 and whole = 20. What does SELECT 100 * (part / whole), 100.0 * part / whole FROM totals return?
  1. 35, 35.0
  2. 0, 0.0
  3. 0, 35.0
  4. 35, 0.0
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A recursive sequence starts at k = 3 and uses SELECT k + 2 FROM seq WHERE k <= 7 with UNION ALL. What values does the CTE contain?
  1. 3, 5, 7
  2. 3, 5, 7, 9
  3. 3, 4, 5, 6, 7
  4. 5, 7, 9
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A hierarchy has root R, children S and T, and U below S. A recursive CTE anchors R at depth 0 and walks down, applying WHERE current.depth < 2 inside its recursive member. The final query keeps depth > 0. What rows remain?
  1. R/0, S/1, T/1
  2. S/1, T/1
  3. U/2 only
  4. S/1, T/1, U/2
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A path starts at node X and follows X → Y, Y → Z, and Z → Y. Its recursive member refuses a destination already on the current path. Which node sequence remains on this route?
  1. X, Y, Z, Y
  2. X, Y, Z
  3. Y, Z
  4. X, Y
Show answerHide answer

Save this lesson to see this answer.

Set 4: Audit equivalent queries and recursive reports10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

In PostgreSQL, SELECT fee FROM plans WHERE plan_id = 99 returns no rows. What value does that subquery contribute when used as a scalar expression?
  1. 0
  2. An empty text string
  3. NULL
  4. A cardinality error
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Teams A, B, and C have 2, 0, and 1 tickets. In PostgreSQL, a report starts from teams, left joins tickets, groups by team, and uses COUNT(*) AS n. A second query averages n. What result is produced, and what change gives the average ticket count across all teams?
  1. It produces 1; replace the left join with an inner join.
  2. It produces 1.5; average DISTINCT n in the outer query.
  3. It produces 1; replace COUNT(*) with SUM(team_id).
  4. It produces 4/3; count the non-null ticket key to get 1.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Required skills are Q and R, each once and non-null. Completed skills are Ada: Q, Q; Bo: Q, R, S; Cy: R. A query joins completions to requirements, groups by person, then uses HAVING COUNT(*) = 2. Who does it return, and how should it be repaired to test every required skill?
  1. Ada and Bo; use COUNT(DISTINCT completed.skill).
  2. Bo only; remove the join to include completed skill S.
  3. Ada only; use COUNT(*) over all completed skills.
  4. Bo and Cy; use COUNT(DISTINCT completed.person).
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A left join finds assets with no inspections using WHERE i.note IS NULL. Inspection IDs are non-null keys, but notes may be null. An asset has one inspection with a null note. What does the query do, and what is the appropriate absence test?
  1. Excludes the asset; test a.asset_id IS NULL instead.
  2. Includes the asset; test i.inspection_id IS NULL instead.
  3. Includes the asset; move i.note IS NULL into ON.
  4. Excludes the asset; change the join to an inner join.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Two members have the same name "Sam". Member 1 has two bookings and member 2 has none. Booking IDs are non-null primary keys. An original query uses correlated NOT EXISTS to find members without bookings and selects name only. A proposed rewrite uses a left join with b.booking_id IS NULL inside ON, then selects DISTINCT m.name. What happens?
  1. It correctly returns one Sam and always preserves the original meaning.
  2. It returns two Sam rows because left joins keep both member identities.
  3. It returns no rows because no booking satisfies the null-key condition.
  4. It returns one Sam but wrongly qualifies both members before DISTINCT.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

In PostgreSQL, branch 1 selects city AS label, 'current' AS source and branch 2 selects city, 'archive'. Both contain the city Quito once. Combined with UNION, what rows and column names result?
  1. Two rows; columns label and source.
  2. One row; columns label and source.
  3. Two rows; columns city and source.
  4. One row; columns city and archive.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Four stores have revenue totals 60, 20, 0, and 0. A report must show stores above the all-store average and each qualifying store's share of all revenue. A draft CTE starts from sales only and another CTE averages its store totals. What above-average result, comparison average, and revenue share should the corrected report show?
  1. Stores 60 and 20; average 20; shares 75% and 25%.
  2. Store 60 only; average 40 and share 75%.
  3. Store 60 only; average 20 and share 75%.
  4. Store 20 only; average 20 and share 25%.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A SQLite report must list daily check-in counts for every date from 2026-06-10 through 2026-06-12. Only June 11 has check-ins, with two rows. How should a recursive date series be combined with check-ins?
  1. Inner join from the dates and count the check-in key.
  2. Left join from the dates and count the check-in key.
  3. Left join from the check-ins and count every row.
  4. Inner join from the check-ins and count every row.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A product P needs two assemblies A and three assemblies B. Each A needs three clips and each B needs two clips. A recursive CTE carries only (component, total_qty) and uses recursive UNION in PostgreSQL. The main query sums quantities by component. What clip total does it report, and why?
  1. 12, because two different parent assemblies remain distinct.
  2. 24, because each clip quantity is multiplied twice.
  3. 0, because repeated components stop the whole recursion.
  4. 6, because the two identical clip-contribution rows merge.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A route graph contains A → B, A → C, B → D, C → D, and D → B. A PostgreSQL recursive query anchors A with path A, uses UNION ALL, and blocks a next node already on that path. Its final query selects node without DISTINCT. How many D rows return, and does the recursion terminate?
  1. Two D rows; the recursion terminates.
  2. One D row; the recursion terminates.
  3. Two D rows; the recursion does not terminate.
  4. One D row; the recursion does not terminate.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

58 Key Terms, each with its definition

A

Adjacency list
An adjacency list represents parent-child links by storing each row's parent key, allowing repeated joins to follow a hierarchy.
Each employee's manager_id points to another employee row that can be followed upward.
ALL
The ALL operator requires every returned comparison to be true and is true for an empty result because no comparison fails.
A price of 6.00 is not greater than ALL stationery prices when that list contains 4.00 and 6.00.
Anchor member
The anchor member is the nonrecursive query that supplies a recursive CTE's starting rows before expansion begins.
An anchor returning 1 starts a sequence whose recursive member adds one at each following step.
Anti-join
An anti-join keeps left-side rows for which no related right-side row matches, often expressed with a correlated NOT EXISTS filter.
Customers with no orders survive the anti-join because no order row matches their customer IDs.
ANY
The ANY operator makes a comparison true when at least one comparison with a returned value is true; it is false for an empty result.
A price of 6.00 is greater than ANY of the stationery prices 4.00 and 6.00 because it exceeds 4.00.

B

Bill of materials
A bill of materials describes assemblies, components, and quantities, allowing recursive multiplication along paths and summation across routes.
In a bicycle whose two wheels need 32 spokes each, the wheels contribute 64 spokes to the bicycle's component requirement.

C

Cardinality
The cardinality of a query result is its number of rows, which must fit the role in which the surrounding statement uses it.
A two-row result violates the cardinality requirement of a scalar subquery, even if the values match.
COALESCE
The COALESCE function returns the first non-null expression in its argument list, allowing a missing aggregate value to be replaced deliberately.
A left-joined customer total uses COALESCE(SUM(o.amount), 0) to represent no spending as zero.
Column subquery
A column subquery returns one column with any number of rows, providing a list of values for a supported membership or comparison test.
A column subquery selects customer IDs from orders to identify customers who have placed an order.
Common table expression
A common table expression is a named query result defined in a WITH clause and available within the single statement that follows it.
A CTE named customer_totals holds one total per customer so a final query can compare each total with the average.
Correlated subquery
A correlated subquery contains an outer reference, so its result is defined using the current row of the surrounding query.
The current product's category selects which inner product rows contribute to its comparison average.
CTE chain
A CTE chain defines named results in dependency order within one WITH clause, allowing later steps to read earlier results.
A second CTE averages customer totals computed by the first CTE before the main query filters them.
CTE column list
A CTE column list explicitly names the result columns after the CTE name, using names that correspond to the query's output positions.
Writing customer_totals(customer_id, total) names the grouped key and amount for later steps.
Cycle
A cycle is a route that leads back to a node already visited on that route, allowing unguarded recursive expansion to repeat indefinitely.
The route A → B → C → A revisits A and needs a cycle rule when recursive rows continue to differ.

D

Date series
A date series is a generated result containing every date in a chosen range, which can supply report rows for dates with no events.
When five of seven generated March dates have no orders, left joining the dates to orders keeps those five days visible with zero orders.
Depth
The depth of a traversal row is its number of steps from the chosen starting level, with the anchor's initial depth set by the query.
If Raj manages Tom, starting Tom at depth 0 places Raj at depth 1 when the recursive query follows Tom's managers.
Depth cap
A depth cap is a recursive condition that bounds how far expansion can go, guaranteeing a limit even when repeated nodes remain in the result.
A hop-0 anchor with hops < 5 permits six levels, from 0 through 5, even along a cycle.
Derived table
A derived table is a subquery in FROM whose output rows and columns become a table that the surrounding query can read.
A derived table holds per-customer order counts so the outer query can average those counts.

E

Entity key
An entity key is a column or column combination that uniquely identifies an entity, preserving its identity when displayed values repeat.
Including customer ID with the name prevents DISTINCT from merging two customers called Lee.
EXCEPT
The EXCEPT operator returns left-input rows absent from the right input, normally as distinct rows; reversing its inputs changes the question.
March customer IDs minus April customer IDs identify customers active in March who did not order in April.
EXISTS
The EXISTS operator returns true when a subquery produces at least one row and false when it produces none, regardless of ordinary selected values.
A correlated EXISTS test keeps a customer once even when the inner query finds several orders.

F

Frontier
A frontier is the newly reached set of rows available for the next recursive expansion, separate from the complete accumulated result.
After two managers form the frontier, the next downward step reaches an employee who reports to one of them.

G

Graph
A graph is a set of nodes linked by edges, where one node may be reached through several parents or routes and cycles may occur.
In a course prerequisite graph, DB201 is reached directly from DB401 and also indirectly through DB301.
Greatest per group
A greatest-per-group query selects rows whose value equals their own group's maximum, including every tied maximum unless another rule narrows it.
Two products tied at the highest price in one category both pass a correlated maximum test.

I

IN
The IN operator tests whether a value equals any value returned by its list or subquery, without multiplying the outer row for repeated matches.
A customer ID appearing three times in an IN list of order customer IDs still keeps its outer customer row once.
Integer division
Integer division divides integer operands and discards the fractional part in systems such as PostgreSQL, SQL Server, and SQLite.
Multiplying a revenue total by 100.0 before dividing prevents an integer quotient from becoming zero.
INTERSECT
The INTERSECT operator returns rows appearing in both compatible results, normally removing duplicates unless the supported ALL variant is used.
If both city lists include Lisbon and Toronto, intersecting customer cities with store cities finds them as shared locations.

J

Join multiplicity
Join multiplicity is the number of matching pairs a join produces for an input row, which can repeat that row's displayed values.
Three orders matched to one customer create three joined rows, although a membership filter keeps that customer once.

M

Multiset
A multiset is a collection in which repeated occurrences matter, as in the duplicate-count rules for INTERSECT ALL and EXCEPT ALL.
Three left copies of a row minus two right copies leave one copy under EXCEPT ALL.

N

NOT EXISTS
The NOT EXISTS operator returns true when a subquery has no rows, making it useful for finding the absence of a related match.
A customer qualifies as having no orders when the correlated order lookup returns an empty result.
NOT IN
The NOT IN operator tests inequality to every returned value; with a scalar list containing NULL, it cannot produce true.
A null manager ID prevents an unfiltered NOT IN manager list from finding employees who manage nobody.

O

Operator precedence
Operator precedence determines which operations are grouped first when a statement combines different operators without explicit grouping.
PostgreSQL groups an intersection before a surrounding union, while SQLite evaluates set operators left to right.
Outer query
An outer query is the surrounding query that reads a nested query's result or supplies values referenced by a correlated subquery.
The outer query selects product names after comparing each product price with an average computed by a nested query.
Outer reference
An outer reference is a column reference inside a subquery that resolves to a table belonging to a surrounding query scope.
In a subquery's category condition, p.category refers to the product row being tested in the outer query.

P

Path
A path is the ordered route of nodes followed to reach a recursive result row, useful for showing ancestry or tracking visited nodes.
The path "Maya > Omar > Raj > Tom" records the sequence leading from the root to Tom.
Population
A report's population is the full group of entities its calculation represents, including zero-event entities when the question requires them.
An all-customer average includes customers with zero spending, which lowers the mean.

Q

Query scope
A query scope is the area where query names are resolved; unqualified columns are searched locally before surrounding scopes.
A missing inner column name may silently resolve to a customer column in the surrounding query.

R

Recursion limit
A recursion limit is a database safeguard that can abort a recursive statement after too many expansion levels, without repairing its logic.
SQL Server uses a default limit of 100 recursive levels, adjustable with MAXRECURSION.
Recursive CTE
A recursive CTE refers to its own result to produce further rows, combining starting rows with repeated expansion until no next rows remain.
A recursive number sequence can generate every day needed for a report before events are attached.
Recursive member
The recursive member is the part of a recursive CTE that reads newly produced rows and uses them to generate the next rows.
Matching employees to the current frontier finds the next level below the current managers.
Relational division
Relational division finds candidates related to every required item, often by checking that no required item is missing for a candidate.
A student with every required course qualifies even if the student has completed extra courses.
Row meaning
The row meaning of an intermediate result states what each row represents, such as one order, one customer total, or one overall average.
A customer-total step should have one row per included customer before it is joined to display names.
Row subquery
A row subquery returns several columns and at most one row, allowing a supported row-value comparison against one corresponding tuple.
A row subquery restricted to one order can supply that order's customer ID and date as a pair.
Row value
A row value is an ordered group of values treated together in a comparison, with corresponding positions compared as one tuple.
The pair (customer_id, order_date) can identify orders matching each customer's latest date.

S

Scalar subquery
A scalar subquery returns one column and at most one row, supplying a single value or NULL when no row is returned.
A scalar subquery containing MAX(order_date) supplies the latest date for a particular customer.
Semi-join
A semi-join keeps each qualifying left-side row when the right side has a match, without returning one row per matching pair.
Using EXISTS to list customers with orders acts as a semi-join and keeps a customer with three orders once, not three times.
Set operation
A set operation combines two compatible query results by stacking or comparing whole rows, with duplicate handling set by the chosen operator.
Current and archived order results can be stacked before their retained amounts are added.
Stopping condition
A stopping condition prevents further recursive expansion when a boundary is reached, so the next recursive step eventually produces no rows.
The condition k < 5 stops an incrementing series when input 5 can no longer produce 6.
Subquery
A subquery is a query nested inside another SQL statement, whose result supplies a value, a list, or a table to that statement.
A subquery can compute the average product price before the outer query tests individual products.

T

Table alias
A table alias is a temporary name for a table reference or derived result, used to identify its columns within a query.
The alias per_customer names the grouped result in a two-stage order-count calculation.
Two-stage aggregation
Two-stage aggregation first creates grouped values at one query level, then applies another aggregate to those values at a second level.
A shop counts orders per customer before averaging the resulting counts across those customers.

U

UNION
The UNION operator returns distinct whole rows from either input, removing duplicates both within and across the input results.
Repeated Lisbon rows collapse to one city when customer and store city lists are combined with UNION.
UNION ALL
The UNION ALL operator stacks every row occurrence from both inputs, preserving repeats that may represent separate events or contributions.
Two orders with equal amounts both contribute to revenue when their lists are stacked with UNION ALL.
Union compatibility
Union compatibility requires the same column count and compatible types in corresponding column positions before two results can be combined.
Selecting name then city in both branches keeps their text values under the intended headings.
Unknown
Unknown is the SQL truth result of an ordinary comparison involving NULL; a WHERE clause keeps only conditions that are true.
A candidate with no known match can still fail NOT IN because comparison with a list null is unknown.
Unmatched row
An unmatched row in a left join is a preserved left-side row with nulls supplied for the columns of the missing right-side match.
A non-null order key becomes null only on unmatched customer rows in a left-join test for customers without orders.

V

View
A view is a query definition stored in the database schema so its name can be used across statements, unlike a statement-scoped CTE.
A one-statement customer-total CTE disappears; a stored view definition remains available afterward.
Visited-path check
A visited-path check prevents a recursive step from entering a node already on its current route, while allowing separate routes to share destinations.
The step from C back to A is rejected when A already appears in the current route's recorded path.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started