Basic CTE: Artist Album Counts
Common Table Expressions (CTEs) let you define named subqueries that make complex queries more readable. Let's start...
Common Table Expressions (CTEs) let you define named subqueries that make complex queries more readable. Let's start...
Use a CTE to find the longest track in each genre. CTEs are especially useful when you need to reference aggregated...
Use multiple CTEs to perform a comprehensive customer analysis: calculate total spending and invoice count, then...
The marketing team wants to identify above-average spenders within each country to target premium campaigns. Compare...
Finance needs a revenue growth analysis showing monthly revenue alongside the previous month and the percentage growth...
The international marketing team needs to know the most popular music genre in each country by purchase count. This...
The CRM team wants to segment customers into value tiers based on their lifetime spending. Classify each customer as...
Management wants to compare the sales performance of support representatives. Calculate each rep's customer count,...
The finance team needs a cumulative revenue growth chart for key markets. Show monthly revenue alongside the running...
The product team wants to identify customers with the most diverse music taste — those who listen across many genres....
The data team discovered that some artists have tracks in multiple genres. Find these cross-genre artists and show...
The retention team wants to understand purchase frequency patterns. Calculate the average, minimum, and maximum gap (in...
The analytics team wants to track how genre popularity changes over time. Calculate the year-over-year revenue change...
Apply the Pareto principle (80/20 rule) to customer revenue. Find the top 20% of customers and show what percentage of...
Compute cohort retention: for each customer signup-month (first invoice), how many of that cohort were active in month...
Track your streak & earn XP
Sign up free to unlock your progress dashboard, daily streaks, and leaderboard ranking.
10 role-based tests for Data Analysts, SQL Developers & Data Engineers with instant scorecards.
Name a step with WITH and use it like a table in the rest of the query.
A common table expression is a named result set defined with WITH at the top of a query and referenced like a table further down. CTEs let a long query be written as a sequence of readable steps instead of nested subqueries, and a recursive CTE can walk a hierarchy or generate a series of dates. In interviews they are usually the difference between an answer a reviewer can follow and one they have to unpick from the inside out.
FAQ
Short answers to what people get stuck on most. Tap a question to expand it.
A CTE (common table expression) is a named result defined with WITH that the rest of the query can use like a table.
WITH paid AS (
SELECT * FROM orders WHERE status = 'paid'
),
by_customer AS (
SELECT customer_id, SUM(amount) AS total
FROM paid
GROUP BY customer_id
)
SELECT * FROM by_customer WHERE total > 500;Not by itself. A CTE mainly makes the query easier to read.
Use WITH RECURSIVE when rows point to other rows in the same table, like managers and their reports.
WITH RECURSIVE chain AS (
SELECT id, manager_id, 1 AS depth
FROM employees WHERE id = 7
UNION ALL
SELECT e.id, e.manager_id, c.depth + 1
FROM employees e
JOIN chain c ON e.id = c.manager_id
)
SELECT * FROM chain;