Querydrill

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.

Start practicing free

Follow a study plan

Practice by topic

Filter by difficulty and pattern

161 exercises

Level 1: Basics

SELECT, WHERE, AND and OR, ORDER BY, LIMIT and OFFSET, DISTINCT, IN, BETWEEN, LIKE, NULL handling, COALESCE and CASE.

  1. Pick two columnsEasy, Filter and sort
  2. Filter rowsEasy, Filter and sort
  3. Top three earnersEasy, Filter and sort
  4. Count paid ordersEasy, Aggregate and group
  5. Each country onceEasy, Filter and sort
  6. Small ordersEasy, Filter and sort
  7. Two countriesEasy, Filter and sort
  8. A date rangeEasy, Filter and sort
  9. Combine AND with OREasy, Filter and sort
  10. Pattern matchEasy, Filter and sort
  11. No managerEasy, NULL handling
  12. Replace NULL with a defaultEasy, NULL handling
  13. Sort on two columnsEasy, Filter and sort
  14. Skip rows with OFFSETEasy, Filter and sort
  15. Calculated columnEasy, Filter and sort
  16. Glue text togetherEasy, Filter and sort
  17. Label with CASEEasy, Conditional counts and pivots
  18. Upper case and lengthEasy, Filter and sort
  19. Search without caring about case (ILIKE)Easy, Filter and sort
  20. 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.

  1. Customers per countryEasy, Aggregate and group
  2. Spend per customerEasy, Aggregate and group
  3. Repeat buyersEasy, Aggregate and group
  4. Customers over a spending thresholdEasy, Aggregate and group
  5. Revenue by monthEasy, Dates and periods
  6. Average salary per departmentEasy, Aggregate and group
  7. First and last orderEasy, Dates and periods
  8. Orders per statusEasy, Aggregate and group
  9. Products per categoryEasy, Aggregate and group
  10. Units sold per productEasy, Aggregate and group
  11. Customers who orderedEasy, Aggregate and group
  12. Average paid orderEasy, Aggregate and group
  13. Hires per yearEasy, Dates and periods
  14. Active in several monthsMedium, Dates and periods
  15. Paid and refunded per customerMedium, Conditional counts and pivots
  16. Share of paid ordersMedium, Shares and rates
  17. Salary bandsMedium, Conditional counts and pivots
  18. Count the missing valuesEasy, NULL handling
  19. Paid revenue per quarterMedium, Dates and periods
  20. Several counts in one pass (FILTER)Medium, Conditional counts and pivots
  21. Paid revenue per week (date_trunc)Medium, Dates and periods
  22. Orders per weekday (EXTRACT)Easy, Dates and periods
  23. Subtotals and a grand total (ROLLUP)Medium, Aggregate and group
  24. 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.

  1. Orders with customer namesEasy, Join tables
  2. Customers who never orderedMedium, Rows with no match
  3. Revenue per countryMedium, Join tables
  4. Everyone with a departmentEasy, Join tables
  5. Employee and managerMedium, Self joins and pairs
  6. Revenue per productMedium, Join tables
  7. Revenue per categoryMedium, Join tables
  8. Products never soldMedium, Rows with no match
  9. Headcount per departmentMedium, Join tables
  10. Orders per customerMedium, Join tables
  11. Most recent order per customerMedium, Join tables
  12. Products per orderEasy, Aggregate and group
  13. Customers from the same countryMedium, Self joins and pairs
  14. Customers who never had a refundMedium, Rows with no match
  15. Employees who manage nobodyMedium, Rows with no match
  16. Categories per customerMedium, Join tables
  17. Payroll per departmentMedium, Join tables
  18. Direct reports per managerMedium, Self joins and pairs
  19. Stack two lists with UNION ALLEasy, Combine and compare sets
  20. Keep both sides with a full joinMedium, Join tables
  21. Products on each order as one text (string_agg)Medium, Join tables
  22. Customers whose every order is paid (bool_and)Medium, Rows with no match
  23. Revenue inflated by a join (fan-out)Medium, Join tables
  24. Not equal, and the rows with NULLMedium, NULL handling
  25. Overlapping bookingsMedium, Self joins and pairs
  26. 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.

  1. Above the average salaryMedium, Compare with an average
  2. Rank within departmentHard, Ranking and top N per group
  3. Running revenue totalHard, Running totals and moving windows
  4. Running total per customerHard, Running totals and moving windows
  5. Top earner per departmentHard, Ranking and top N per group
  6. Second highest salaryMedium, Ranking and top N per group
  7. Big spendersMedium, Compare with an average
  8. Levels in the reporting chainHard, Hierarchies and generated rows
  9. Dense rankMedium, Ranking and top N per group
  10. Change from the previous orderHard, Previous and next row
  11. Days until the next orderHard, Previous and next row
  12. Moving averageHard, Running totals and moving windows
  13. Share of revenueMedium, Shares and rates
  14. Share of the customer's totalHard, Shares and rates
  15. Each customer's first orderHard, Ranking and top N per group
  16. Month over monthHard, Previous and next row
  17. Top two per categoryHard, Ranking and top N per group
  18. Orders above the customer's averageMedium, Compare with an average
  19. Compared to the first orderHard, Previous and next row
  20. Salary quartilesHard, Ranking and top N per group
  21. Cumulative share of revenueHard, Running totals and moving windows
  22. Latest order per customer (DISTINCT ON)Medium, Ranking and top N per group
  23. Two largest paid orders per customer (LATERAL)Hard, Ranking and top N per group
  24. Most orders, ties includedMedium, Ranking and top N per group
  25. Last event per user, with a tie-breakMedium, Ranking and top N per group
  26. Year-over-year growthMedium, Dates and periods
  27. Price at the time of the orderHard, Dates and periods
  28. Read fields out of JSONMedium, JSON and arrays
  29. 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.

  1. Third highest salaryHard, Ranking and top N per group
  2. Second highest salary per departmentHard, Ranking and top N per group
  3. Earns more than the managerHard, Self joins and pairs
  4. Departments above averageHard, Compare with an average
  5. Salary against the department averageHard, Compare with an average
  6. Pivot the statusesHard, Conditional counts and pivots
  7. Repeat purchase rateHard, Shares and rates
  8. Median salaryHard, Ranking and top N per group
  9. Orders in consecutive monthsHard, Gaps and islands
  10. Runs of the same statusHard, Gaps and islands
  11. Cohort retentionHard, Product analytics
  12. Products bought togetherHard, Self joins and pairs
  13. First order not paidHard, Ranking and top N per group
  14. A month with no sales still shows up (generate_series)Hard, Hierarchies and generated rows
  15. Daily active usersEasy, Product analytics
  16. Monthly active usersEasy, Product analytics
  17. Funnel: users at each stepEasy, Product analytics
  18. Signup to purchase conversionHard, Product analytics
  19. New and returning users per dayHard, Product analytics
  20. Day-1 retentionHard, Product analytics
  21. Retention curveHard, Product analytics
  22. Sessions per user (30-minute rule)Hard, Gaps and islands
  23. Rolling 7-day active usersHard, Product analytics
  24. Longest streak of active daysHard, Gaps and islands
  25. Monthly churn rateHard, Product analytics
  26. Reactivated subscribersHard, Previous and next row
  27. Merge bookings into occupied periodsHard, Gaps and islands
  28. 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.

  1. Clean up the country reportMedium, Clean messy data
  2. Find duplicate accountsMedium, Clean messy data
  3. Keep one account per personHard, Clean messy data
  4. Total revenue from text amountsMedium, Clean messy data
  5. Monthly revenue from mixed datesMedium, Clean messy data
  6. Signups per planMedium, Clean messy data
  7. Paying customers by countryHard, Clean messy data
  8. First payment per customerMedium, Clean messy data
  9. Failed payments by monthMedium, Clean messy data
  10. Revenue per planMedium, Clean messy data
  11. Signed up, never paidHard, Rows with no match
  12. 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.

  1. Revenue report, step 1: revenue per monthMedium, Aggregate and group
  2. Revenue report, step 2: change on the previous monthHard, Previous and next row
  3. Revenue report, step 3: running totalHard, Running totals and moving windows
  4. Revenue report, step 4: share of the totalHard, Shares and rates
  5. Customer value, step 1: orders and spend per customerMedium, Join tables
  6. Customer value, step 2: first order, last order, days activeHard, Dates and periods
  7. Customer value, step 3: segment the customersHard, Conditional counts and pivots
  8. Customer value, step 4: summarize the segmentsHard, Conditional counts and pivots
  9. Product performance, step 1: units and revenue per productMedium, Join tables
  10. Product performance, step 2: revenue per categoryMedium, Join tables
  11. Product performance, step 3: best seller in each categoryHard, Ranking and top N per group
  12. Product performance, step 4: products with no paid salesHard, Rows with no match
  13. Refund review, step 1: refund rate per monthMedium, Shares and rates
  14. Refund review, step 2: refund rate per countryMedium, Shares and rates
  15. Refund review, step 3: who gets the refundsMedium, Join tables
  16. Refund review, step 4: refunded value per categoryHard, Join tables
  17. Refund review, step 5: the summary lineHard, Shares and rates
  18. Payroll review, step 1: headcount and payroll per departmentMedium, Aggregate and group
  19. Payroll review, step 2: pay against the company averageMedium, Compare with an average
  20. Payroll review, step 3: the top earner's shareHard, Shares and rates
  21. Payroll review, step 4: hires per year and running headcountHard, Running totals and moving windows
  22. 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