- Learn
- Computer Science & IT
- Programming
- Database Design and Advanced SQL
- SQL Subqueries and CTEs
SQL Subqueries and CTEs: Set Operations
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
- 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 subqueryRecognize 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 FROMTreat 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 ALLCompare 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.
- Compute a single value with a scalar subquery
- 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 subqueriesLink 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 EXISTSUse 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 subqueryRewrite a query between join and subquery forms, and pick the form that returns the right rows and states the question most clearly.
- Write correlated subqueries
- 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 ALLCombine 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 EXCEPTReturn 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.
- Stack results with UNION and UNION ALL
- 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 CTEsWrite 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 stepsBreak a question into intermediate results, write each as a CTE, check each step, and combine them into a correct final answer.
- Define and chain CTEs
- 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 CTEWrite the anchor and recursive members, trace how the rows are produced step by step, and make the recursion stop.
- Walk trees and graphs with recursionFollow 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 cyclesRecognize when recursion would never end, use system limits as a safety net, and stop at cycles by tracking visited rows or depth.
- Build a recursive CTE
SQL Subqueries and CTEs study guide
1Answer 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
| Shape | Result | Typical use |
|---|---|---|
| Scalar | One column, at most one row | A comparison or computed value |
| Column | One column, any number of rows | An IN list |
| Row | Several columns, at most one row | A row-value comparison |
| Table | Any number of rows and columns | A 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 giveNULL.
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_id | customer_id | order_date | amount |
|---|---|---|---|
| 101 | 1 | 2026-03-02 | 30.00 |
| 102 | 2 | 2026-03-05 | 12.00 |
| 103 | 1 | 2026-03-09 | 45.00 |
| 104 | 3 | 2026-03-15 | 8.00 |
| 105 | 2 | 2026-03-20 | 64.00 |
| 106 | 1 | 2026-04-01 | 10.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
| Test | Meaning | Stationery list 4.00, 6.00 |
|---|---|---|
price > ANY (...) | Greater than at least one value | Keeps prices above 4.00 |
price > ALL (...) | Greater than every value | Keeps prices above 6.00 |
price = ANY (...) | Equal to at least one value | Same as IN |
price <> ALL (...) | Different from every value | Same 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
INtests membership without multiplying outer rows.- A null in a scalar
NOT INlist prevents the test from being true. ANYneeds one successful comparison;ALLneeds every comparison to be true.- Over an empty list,
ANYis false andALLis true. <> ANYis not an absence test.- A maximum-based rewrite needs a nonempty, null-free list.
2Compare 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.
2.2 Test for related rows with EXISTS and NOT EXISTS
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
EXISTStests for rows; ordinarySELECT 1existence tests ignore selected values.- Keep the outer-to-inner link inside a correlated existence test.
NOT EXISTSexpresses the absence of a matching row without theNOT INnull 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
| Need | Useful form |
|---|---|
| Customer name beside each order amount | Join customers to orders |
| Customers who have an order | IN or correlated EXISTS |
| Customers without an order | Correlated NOT EXISTS |
| Products above their category average | Correlated 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
DISTINCTmust preserve different people with the same name. - In a left-join absence test, put
IS NULLinWHEREand 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.
3Combine 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
UNIONremoves duplicate whole rows across both inputs;UNION ALLretains all occurrences.- Columns match by position and need compatible types; names come from the first query.
- Write one final
ORDER BYfor 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:
| Operation | Result |
|---|---|
Customers INTERSECT stores | Lisbon, Toronto |
Customers EXCEPT stores | Nairobi, Singapore |
Stores EXCEPT customers | Berlin |
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
INTERSECTkeeps shared rows;EXCEPTsubtracts right-side rows from the left.- Every selected column participates in row matching.
- Set-operation duplicate checks treat corresponding nulls as equal.
INTERSECT ALLkeeps the smaller count;EXCEPT ALLkeeps the nonnegative count difference.- Mixed set operations need explicit grouping when dialect precedence differs.
EXCEPTand equality-basedNOT EXISTSdiffer in duplicate and null handling.
4Organize 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
| Object | What it provides |
|---|---|
| CTE | A named result within one statement |
| View | A query definition stored in the database schema |
| Temporary table | Stored 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
WITHclause. - 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.
- Build one total per customer with orders.
- Average those totals to get one comparison row.
- 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.
5Query 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
UNIONstops 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
CYCLEmarks cycle-closing rows and stops expanding them.
SQL Subqueries and CTEs examples
1Build an answer from an inner result
14 steps
- 1IntroductionChoose 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.
- 2ExampleCreate 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.
- 3ExampleUse 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
WHEREtests individual rows, while the inner query has its own aggregation level. WritingAVGdirectly in the sameWHEREwould not create that separate level. - 4ChallengePredict 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 withNULLis unknown.WHEREkeeps only true conditions. This is different from an emptyCOUNTaggregate, which still returns one row containing 0. - 5ExampleCount 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.
- 6ExampleRead the grouped result as a table
Wrap the grouped query in
FROMand 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.
- 7ChallengeCheck 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.
- 8ConnectionRecover 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.
- 9ExplanationTest 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.
- 10ExampleTrace one NOT IN comparison
A manager-ID list contains
NULL, 1, 1, 2, 2, and 4. For employee ID 3,NOT INrequires inequality to every listed value.The inequalities with 1, 2, and 4 are true. The inequality with
NULLis 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 correlatedNOT EXISTSabsence test. - 11Key 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.
SOMEis a synonym forANY. Not-equal-toANYalso needs just one success, so it cannot stand in forNOT IN: a value may differ from one list entry while matching another. - 12ChallengeTry an empty category
There are no garden products. Compare a filter using
price > ALL (SELECT price FROM products WHERE category = 'garden')with one usingprice > (SELECT MAX(price) FROM products WHERE category = 'garden'). Which keeps the six non-null product prices?---reveal---
ALLkeeps all six because the list is empty.MAXreturnsNULL, so its ordinary comparison keeps none. A maximum-based rewrite changes the empty-input behavior. - 13ChallengeRepair 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
MAXsubquery meet both requirements unchanged?---reveal---
No.
MAXreturnsNULLfor an empty list and ignoresNULLentries in a nonempty list.ALLhas the required filter behavior. In PostgreSQL,NOT EXISTSof a comparison that IS NOT TRUE can express the same row selection. - 14RecapRead 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
NULLvalues. Empty-listALLand an emptyMAXaggregate behave differently, so a shorter-looking rewrite can change which rows qualify.
2Follow each outer row to its related rows
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake the relationship visible
- 2ExampleGive the product two roles
- 3ExampleTrace the category comparisons
- 4ChallengeSpot the missing owner
- 5TipKeep zero counts and tied maxima
- 6ExplanationTurn a match into a yes-or-no test
- 7ExampleFind customers without orders
- 8ChallengeCheck where the condition belongs
- 9ExampleBuild the missing-course list
- 10Key InsightExpress every as no missing item
- 11ChallengeRemove every requirement
- 12ConnectionRewrite while keeping identities
- 13ChallengeAudit a tempting left-join rewrite
- 14ChallengeCombine a group comparison with details
- 15RecapCheck links and row counts
3Combine lists without losing their meaning
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionChoose what one row means
- 2ExampleStack the two city lists
- 3TipAlign positions and sort once
- 4ChallengePreserve separate revenue events
- 5ExampleFind shared or missing cities
- 6ExampleCompare customer IDs across periods
- 7ExplanationCount repeated rows deliberately
- 8ChallengeCompare a null city
- 9Key InsightMake grouping visible
- 10ChallengeKeep events, then compare keys
- 11RecapMatch rows before choosing operators
4Turn a report into named SQL steps
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionGive each intermediate result a job
- 2ExampleDefine customer totals once
- 3ExampleAdd a dependent step
- 4ChallengeTry to reuse the name later
- 5ExampleCompare totals with the average
- 6Key InsightChange the population in the totals
- 7ChallengePredict a changed difference
- 8ExampleCompute a revenue share
- 9TipFind where rows multiply
- 10ChallengeAudit a complete reporting plan
- 11RecapVerify each named result
5Trace recursion through numbers, trees, and cycles
18 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFollow the next frontier
- 2ExampleWrite an anchor and one recursive step
- 3ExampleTrace the boundary row
- 4ChallengeChoose the condition for an endpoint
- 5ConnectionUse dates to supply missing report rows
- 6ExampleAnchor the direct reports
- 7ExampleJoin to the next employees
- 8ChallengeWalk in the opposite direction
- 9TipCarry a path that can grow
- 10ExampleKeep quantities from different routes
- 11ChallengeChoose whether a repeated destination matters
- 12ExplanationSee why a hop count defeats deduplication
- 13ExampleBlock a city already on the path
- 14ChallengeDistinguish depth caps from visited checks
- 15TipUse system guards as a backup
- 16ChallengeAdvance the selected row as well as the join
- 17ChallengeCombine output needs with termination
- 18RecapAudit the whole recursive row
SQL Subqueries and CTEs practice questions
Set 1: Read results and choose the right query shape10 Practice Questions
Question 1 of 10
price = (SELECT price FROM offers WHERE item_id = 17). That inner query returns two rows, both containing 9.00. What happens?Show answerHide answer
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;
Show answerHide answer
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?Show answerHide answer
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)
Show answerHide answer
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);
Show answerHide answer
v.visitor_id inside the subquery.Question 6 of 10
EXISTS query selects their account IDs and names. What preserves those identities when rewriting it as an inner join?Show answerHide answer
Question 7 of 10
east: 2, 2, 5 and west: 2, 8. How many rows does east UNION ALL west contain?Show answerHide answer
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
A EXCEPT ALL B?Show answerHide answer
EXCEPT, which removes 4 entirely because it occurs on the right.Question 9 of 10
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?Show answerHide answer
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
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?Show answerHide answer
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)?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
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?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);
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?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
UNION, then the outer query sums amount. What is returned?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
counts depends on raw_data. What is the portable structure for defining both in one statement?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
UNION and carries (node, hops), increasing hops at each step. Why can it keep expanding?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)?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
(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?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?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
NOT EXISTS division query and a counting query using an inner join to required certifications return?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
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?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?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
part = 7 and whole = 20. What does SELECT 100 * (part / whole), 100.0 * part / whole FROM totals return?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
k = 3 and uses SELECT k + 2 FROM seq WHERE k <= 7 with UNION ALL. What values does the CTE contain?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
WHERE current.depth < 2 inside its recursive member. The final query keeps depth > 0. What rows remain?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
SELECT fee FROM plans WHERE plan_id = 99 returns no rows. What value does that subquery contribute when used as a scalar expression?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
COUNT(*) AS n. A second query averages n. What result is produced, and what change gives the average ticket count across all teams?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
HAVING COUNT(*) = 2. Who does it return, and how should it be repaired to test every required skill?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
(component, total_qty) and uses recursive UNION in PostgreSQL. The main query sums quantities by component. What clip total does it report, and why?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Adjacency list
manager_id points to another employee row that can be followed upward.ALL
ALL operator requires every returned comparison to be true and is true for an empty result because no comparison fails.ALL stationery prices when that list contains 4.00 and 6.00.Anchor member
Anti-join
NOT EXISTS filter.ANY
ANY operator makes a comparison true when at least one comparison with a returned value is true; it is false for an empty result.ANY of the stationery prices 4.00 and 6.00 because it exceeds 4.00.B
Bill of materials
C
Cardinality
COALESCE
COALESCE function returns the first non-null expression in its argument list, allowing a missing aggregate value to be replaced deliberately.COALESCE(SUM(o.amount), 0) to represent no spending as zero.Column subquery
Common table expression
WITH clause and available within the single statement that follows it.customer_totals holds one total per customer so a final query can compare each total with the average.Correlated subquery
CTE chain
WITH clause, allowing later steps to read earlier results.CTE column list
customer_totals(customer_id, total) names the grouped key and amount for later steps.Cycle
D
Date series
Depth
Depth cap
hops < 5 permits six levels, from 0 through 5, even along a cycle.Derived table
FROM whose output rows and columns become a table that the surrounding query can read.E
Entity key
DISTINCT from merging two customers called Lee.EXCEPT
EXCEPT operator returns left-input rows absent from the right input, normally as distinct rows; reversing its inputs changes the question.EXISTS
EXISTS operator returns true when a subquery produces at least one row and false when it produces none, regardless of ordinary selected values.EXISTS test keeps a customer once even when the inner query finds several orders.F
Frontier
G
Graph
Greatest per group
I
IN
IN operator tests whether a value equals any value returned by its list or subquery, without multiplying the outer row for repeated matches.IN list of order customer IDs still keeps its outer customer row once.Integer division
100.0 before dividing prevents an integer quotient from becoming zero.INTERSECT
INTERSECT operator returns rows appearing in both compatible results, normally removing duplicates unless the supported ALL variant is used.J
Join multiplicity
M
Multiset
INTERSECT ALL and EXCEPT ALL.EXCEPT ALL.N
NOT EXISTS
NOT EXISTS operator returns true when a subquery has no rows, making it useful for finding the absence of a related match.NOT IN
NOT IN operator tests inequality to every returned value; with a scalar list containing NULL, it cannot produce true.NOT IN manager list from finding employees who manage nobody.O
Operator precedence
Outer query
Outer reference
p.category refers to the product row being tested in the outer query.P
Path
Population
Q
Query scope
R
Recursion limit
MAXRECURSION.Recursive CTE
Recursive member
Relational division
Row meaning
Row subquery
Row value
(customer_id, order_date) can identify orders matching each customer's latest date.S
Scalar subquery
NULL when no row is returned.MAX(order_date) supplies the latest date for a particular customer.Semi-join
EXISTS to list customers with orders acts as a semi-join and keeps a customer with three orders once, not three times.Set operation
Stopping condition
k < 5 stops an incrementing series when input 5 can no longer produce 6.Subquery
T
Table alias
per_customer names the grouped result in a two-stage order-count calculation.Two-stage aggregation
U
UNION
UNION operator returns distinct whole rows from either input, removing duplicates both within and across the input results.UNION.UNION ALL
UNION ALL operator stacks every row occurrence from both inputs, preserving repeats that may represent separate events or contributions.UNION ALL.Union compatibility
Unknown
NULL; a WHERE clause keeps only conditions that are true.NOT IN because comparison with a list null is unknown.Unmatched row
V
View
Visited-path check
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.