All 161 SQL exercises
Every answer is checked twice: on the rows you see, and again on a changed copy of the data you do not see. A typed-in value fails; only a working query passes. Real PostgreSQL runs in your browser, with nothing to install. The exercises are listed here level by level. Your first 8 exercises are free without an account, from any level; Pro unlocks all 161.
Follow a study plan
- 14-day SQL interview sprint (41)
- SQL for data analyst interviews (24)
- SQL for BI analyst interviews (21)
- SQL for data engineer interviews (24)
- Product analytics SQL in four sessions (12)
- SQL traps and time periods in three sessions (10)
- Window functions in six sessions (18)
- SQL on messy data: one work week (16)
- PostgreSQL features in four sessions (11)
Practice by topic
Filter by difficulty and pattern
Level 1: Basics
SELECT, WHERE, AND and OR, ORDER BY, LIMIT and OFFSET, DISTINCT, IN, BETWEEN, LIKE, NULL handling, COALESCE and CASE.
- Pick two columnsEasy, Filter and sort
- Filter rowsEasy, Filter and sort
- Top three earnersEasy, Filter and sort
- Count paid ordersEasy, Aggregate and group
- Each country onceEasy, Filter and sort
- Small ordersEasy, Filter and sort
- Two countriesEasy, Filter and sort
- A date rangeEasy, Filter and sort
- Combine AND with OREasy, Filter and sort
- Pattern matchEasy, Filter and sort
- No managerEasy, NULL handling
- Replace NULL with a defaultEasy, NULL handling
- Sort on two columnsEasy, Filter and sort
- Skip rows with OFFSETEasy, Filter and sort
- Calculated columnEasy, Filter and sort
- Glue text togetherEasy, Filter and sort
- Label with CASEEasy, Conditional counts and pivots
- Upper case and lengthEasy, Filter and sort
- Search without caring about case (ILIKE)Easy, Filter and sort
- Full years of service (age)Easy, Dates and periods
Level 2: Aggregation
COUNT, SUM, AVG, GROUP BY, HAVING, COUNT DISTINCT, percentages, whole-number division and grouping by dates.
- Customers per countryEasy, Aggregate and group
- Spend per customerEasy, Aggregate and group
- Repeat buyersEasy, Aggregate and group
- Customers over a spending thresholdEasy, Aggregate and group
- Revenue by monthEasy, Dates and periods
- Average salary per departmentEasy, Aggregate and group
- First and last orderEasy, Dates and periods
- Orders per statusEasy, Aggregate and group
- Products per categoryEasy, Aggregate and group
- Units sold per productEasy, Aggregate and group
- Customers who orderedEasy, Aggregate and group
- Average paid orderEasy, Aggregate and group
- Hires per yearEasy, Dates and periods
- Active in several monthsMedium, Dates and periods
- Paid and refunded per customerMedium, Conditional counts and pivots
- Share of paid ordersMedium, Shares and rates
- Salary bandsMedium, Conditional counts and pivots
- Count the missing valuesEasy, NULL handling
- Paid revenue per quarterMedium, Dates and periods
- Several counts in one pass (FILTER)Medium, Conditional counts and pivots
- Paid revenue per week (date_trunc)Medium, Dates and periods
- Orders per weekday (EXTRACT)Easy, Dates and periods
- Subtotals and a grand total (ROLLUP)Medium, Aggregate and group
- Average lines per order (whole-number division)Easy, Shares and rates
Level 3: Joins
Inner, left, full and self joins, UNION ALL and EXCEPT, rows with no match, zero counts, joins that inflate a total, overlapping periods.
- Orders with customer namesEasy, Join tables
- Customers who never orderedMedium, Rows with no match
- Revenue per countryMedium, Join tables
- Everyone with a departmentEasy, Join tables
- Employee and managerMedium, Self joins and pairs
- Revenue per productMedium, Join tables
- Revenue per categoryMedium, Join tables
- Products never soldMedium, Rows with no match
- Headcount per departmentMedium, Join tables
- Orders per customerMedium, Join tables
- Most recent order per customerMedium, Join tables
- Products per orderEasy, Aggregate and group
- Customers from the same countryMedium, Self joins and pairs
- Customers who never had a refundMedium, Rows with no match
- Employees who manage nobodyMedium, Rows with no match
- Categories per customerMedium, Join tables
- Payroll per departmentMedium, Join tables
- Direct reports per managerMedium, Self joins and pairs
- Stack two lists with UNION ALLEasy, Combine and compare sets
- Keep both sides with a full joinMedium, Join tables
- Products on each order as one text (string_agg)Medium, Join tables
- Customers whose every order is paid (bool_and)Medium, Rows with no match
- Revenue inflated by a join (fan-out)Medium, Join tables
- Not equal, and the rows with NULLMedium, NULL handling
- Overlapping bookingsMedium, Self joins and pairs
- Compare two tables (EXCEPT)Medium, Combine and compare sets
Level 4: Advanced
Subqueries, CTEs, recursive CTEs, RANK, DENSE_RANK, ROW_NUMBER, LAG and LEAD, running totals, ties, year-over-year growth, point-in-time prices and JSON.
- Above the average salaryMedium, Compare with an average
- Rank within departmentHard, Ranking and top N per group
- Running revenue totalHard, Running totals and moving windows
- Running total per customerHard, Running totals and moving windows
- Top earner per departmentHard, Ranking and top N per group
- Second highest salaryMedium, Ranking and top N per group
- Big spendersMedium, Compare with an average
- Levels in the reporting chainHard, Hierarchies and generated rows
- Dense rankMedium, Ranking and top N per group
- Change from the previous orderHard, Previous and next row
- Days until the next orderHard, Previous and next row
- Moving averageHard, Running totals and moving windows
- Share of revenueMedium, Shares and rates
- Share of the customer's totalHard, Shares and rates
- Each customer's first orderHard, Ranking and top N per group
- Month over monthHard, Previous and next row
- Top two per categoryHard, Ranking and top N per group
- Orders above the customer's averageMedium, Compare with an average
- Compared to the first orderHard, Previous and next row
- Salary quartilesHard, Ranking and top N per group
- Cumulative share of revenueHard, Running totals and moving windows
- Latest order per customer (DISTINCT ON)Medium, Ranking and top N per group
- Two largest paid orders per customer (LATERAL)Hard, Ranking and top N per group
- Most orders, ties includedMedium, Ranking and top N per group
- Last event per user, with a tie-breakMedium, Ranking and top N per group
- Year-over-year growthMedium, Dates and periods
- Price at the time of the orderHard, Dates and periods
- Read fields out of JSONMedium, JSON and arrays
- One row per array elementMedium, JSON and arrays
Level 5: Interview classics
Nth highest salary, median, pivots with CASE, gaps and islands, and product analytics on an events table: active users, funnels, retention, sessions, streaks and churn.
- Third highest salaryHard, Ranking and top N per group
- Second highest salary per departmentHard, Ranking and top N per group
- Earns more than the managerHard, Self joins and pairs
- Departments above averageHard, Compare with an average
- Salary against the department averageHard, Compare with an average
- Pivot the statusesHard, Conditional counts and pivots
- Repeat purchase rateHard, Shares and rates
- Median salaryHard, Ranking and top N per group
- Orders in consecutive monthsHard, Gaps and islands
- Runs of the same statusHard, Gaps and islands
- Cohort retentionHard, Product analytics
- Products bought togetherHard, Self joins and pairs
- First order not paidHard, Ranking and top N per group
- A month with no sales still shows up (generate_series)Hard, Hierarchies and generated rows
- Daily active usersEasy, Product analytics
- Monthly active usersEasy, Product analytics
- Funnel: users at each stepEasy, Product analytics
- Signup to purchase conversionHard, Product analytics
- New and returning users per dayHard, Product analytics
- Day-1 retentionHard, Product analytics
- Retention curveHard, Product analytics
- Sessions per user (30-minute rule)Hard, Gaps and islands
- Rolling 7-day active usersHard, Product analytics
- Longest streak of active daysHard, Gaps and islands
- Monthly churn rateHard, Product analytics
- Reactivated subscribersHard, Previous and next row
- Merge bookings into occupied periodsHard, Gaps and islands
- Peak number of bookings at onceHard, Running totals and moving windows
Level 6: Work mode
Requests from Marketing, Finance and Support on messy tables: text amounts, mixed date formats, duplicates and stray spaces.
- Clean up the country reportMedium, Clean messy data
- Find duplicate accountsMedium, Clean messy data
- Keep one account per personHard, Clean messy data
- Total revenue from text amountsMedium, Clean messy data
- Monthly revenue from mixed datesMedium, Clean messy data
- Signups per planMedium, Clean messy data
- Paying customers by countryHard, Clean messy data
- First payment per customerMedium, Clean messy data
- Failed payments by monthMedium, Clean messy data
- Revenue per planMedium, Clean messy data
- Signed up, never paidHard, Rows with no match
- Days from signup to first paymentHard, Clean messy data
Level 7: Case studies
Five business cases built step by step, each answer feeding the next: a monthly revenue report, a customer value analysis, a product performance review, a refund review and a payroll review.
- Revenue report, step 1: revenue per monthMedium, Aggregate and group
- Revenue report, step 2: change on the previous monthHard, Previous and next row
- Revenue report, step 3: running totalHard, Running totals and moving windows
- Revenue report, step 4: share of the totalHard, Shares and rates
- Customer value, step 1: orders and spend per customerMedium, Join tables
- Customer value, step 2: first order, last order, days activeHard, Dates and periods
- Customer value, step 3: segment the customersHard, Conditional counts and pivots
- Customer value, step 4: summarize the segmentsHard, Conditional counts and pivots
- Product performance, step 1: units and revenue per productMedium, Join tables
- Product performance, step 2: revenue per categoryMedium, Join tables
- Product performance, step 3: best seller in each categoryHard, Ranking and top N per group
- Product performance, step 4: products with no paid salesHard, Rows with no match
- Refund review, step 1: refund rate per monthMedium, Shares and rates
- Refund review, step 2: refund rate per countryMedium, Shares and rates
- Refund review, step 3: who gets the refundsMedium, Join tables
- Refund review, step 4: refunded value per categoryHard, Join tables
- Refund review, step 5: the summary lineHard, Shares and rates
- Payroll review, step 1: headcount and payroll per departmentMedium, Aggregate and group
- Payroll review, step 2: pay against the company averageMedium, Compare with an average
- Payroll review, step 3: the top earner's shareHard, Shares and rates
- Payroll review, step 4: hires per year and running headcountHard, Running totals and moving windows
- Payroll review, step 5: managers and their teamsHard, Self joins and pairs
Your first 8 exercises are free.
No sign-up needed. Check your answer on every exercise, from every level. Pro unlocks all 161 exercises, every reference solution, timed mode and the certificate, with a one-time pass and no subscription.
Start practicing free