Lesson Description
A query inside another query.
Lesson 1 of 4
Progress: 0/4 exercises solved (0%)
Solve all exercises below to unlock the next lesson.
Lesson Description
A query inside another query.
Easy Project
Mini project: Turn this lesson into a real-world query artifact by writing one clean business report query and validating output quality.
A subquery is a SELECT statement nested inside another query. It can appear in WHERE, FROM, or SELECT.
Returns a single value and can be used with =, >, <, etc.:
-- Employees earning more than the company average
SELECT first_name, last_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
Returns a column of values; the outer query checks membership:
-- Products that have been ordered at least once
SELECT name
FROM products
WHERE id IN (SELECT DISTINCT product_id FROM order_items);
-- Products never ordered
SELECT name
FROM products
WHERE id NOT IN (SELECT product_id FROM order_items);
Caution: NOT IN returns no rows if the subquery contains any NULL. Prefer NOT EXISTS when NULLs are possible.
Returns TRUE if the subquery returns at least one row:
SELECT first_name, last_name
FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.id
);
A subquery in FROM acts like a temporary table:
SELECT dept, avg_sal
FROM (
SELECT department_id AS dept, AVG(salary) AS avg_sal
FROM employees
GROUP BY department_id
) dept_stats
WHERE avg_sal > 8000;
LIMIT 1 or aggregate if unsure.WITH) is often more readable.This lesson is part of Subqueries & CTEs. Focus on the core idea in Subqueries (IN, EXISTS, scalar), then validate with deliberate practice.
What to master
Common mistakes
High-level strategy
Task ladder
Transparent data checks
Retention loop
Logical reasoning for commands
WHERE
Why: Limits rows to only the business-relevant subset.
Memory cue: Filter early to reduce noise.
ORDER BY
Why: Makes output deterministic and reviewable.
Memory cue: No ORDER BY means no guaranteed row order.
AS alias
Why: Makes output columns readable for teams and reports.
Memory cue: If the name is clear, the query is easier to trust.
Concept check
3 quick questions. One at a time. Instant score at the end.
Return first_name, last_name, and salary of employees earning strictly more than the company average salary.
Return the name of every product that does NOT appear in any order_items row.
Return first_name and last_name of customers who have placed at least one order. Use EXISTS. Order by last_name.
From the store sandbox, return name, price, and category_id for products whose price is strictly above the average price in their own category. Order by category_id, then price descending.
Lesson 1 of 4
0/4 solved (0%)
Finish this lesson to unlock next.