Subqueries & CTEs — quiz
8 questions covering this module. Scalar subqueries, derived tables, WITH, and EXISTS versus IN.
A subquery referencing the outer query is:
- Scalar
- Correlated
- Derived
- Recursive
Answer: Correlated — Correlated subqueries are evaluated per outer row.
A correlated COUNT subquery in SELECT is usually better as:
- A CTE
- A LEFT JOIN with GROUP BY
- A UNION
- A window function only
Answer: A LEFT JOIN with GROUP BY — One aggregation pass beats one query per row.
Derived tables in FROM usually require:
- An index
- An alias
- A GROUP BY
- A WHERE clause
Answer: An alias — Most dialects reject an unaliased derived table.
Pre-aggregating before a join prevents:
- Null values
- Row multiplication
- Slow sorting
- Type errors
Answer: Row multiplication — One row per key means nothing fans out.
A recursive CTE requires:
- An index
- An anchor member, UNION ALL and a recursive member
- A window function
- A temporary table
Answer: An anchor member, UNION ALL and a recursive member — Plus something that guarantees termination.
The main advantage of a CTE over nested subqueries is:
- Always faster
- Readable top-to-bottom structure and reuse
- Avoids indexes
- Allows aggregates
Answer: Readable top-to-bottom structure and reuse — Performance depends on whether the engine inlines it.
Safest way to find customers with no orders:
- NOT IN
- NOT EXISTS
- != ANY
- CROSS JOIN
Answer: NOT EXISTS — NOT EXISTS is null-safe; NOT IN is not.
Why is SELECT 1 used inside EXISTS?
- It is faster to parse
- The column list is never evaluated
- It returns a boolean
- It is required syntax
Answer: The column list is never evaluated — EXISTS only cares whether a row exists, not what it contains.