Databases

SQL Practice

Solve real questions on the Shop, Bank and School data, from easy to interview level, and get your answer checked instantly in the browser.

9 chapters 118 problems
Start practising →

Course map

9 chapters in order. Start at the first, or jump to the one you need.

  1. Chapter 1 Select, Filter and Sort Read the right rows and columns in the right order: WHERE, NULL, LIKE, CASE, LIMIT. 13 problems
  2. Chapter 2 Functions, Dates and Cleaning Turn messy real-world columns into clean answers: text, numbers, dates and missing values. 13 problems
  3. Chapter 3 Aggregation and Grouping Summarise thousands of rows into the numbers a manager asks for: COUNT, SUM, AVG, GROUP BY, HAVING and conditional totals. 15 problems
  4. Chapter 4 Joins Combine tables correctly: inner and left joins, finding what is missing, joining a table to itself, and avoiding the traps that inflate your numbers. 16 problems
  5. Chapter 5 Subqueries and CTEs Break a hard question into steps: scalar and correlated subqueries, EXISTS, derived tables, WITH and recursion. 12 problems
  6. Chapter 6 Window Functions Calculate across rows without losing them: ranking, top N per group, running totals, previous and next rows, moving averages. 12 problems
  7. Chapter 7 Business Analytics Answer the questions managers really ask: growth, cohorts, funnels, segments and concentration. Each problem combines several skills. 14 problems
  8. Chapter 8 Interview Puzzles The classic hard questions of SQL interviews: median, duplicates, gaps and islands, division, recursion and year-over-year comparisons. 12 problems
  9. Chapter 9 Changing Data Write INSERT, UPDATE, DELETE, transactions and CREATE TABLE. Your statements run on a private copy, then a check query judges the result. 11 problems

1. Select, Filter and Sort

  1. Expensive Products List the products that cost more than 50, most expensive first. Practice WHERE and ORDER BY on the Shop data.
  2. Customers from Egypt Find the customers whose country is Egypt. Practice a text comparison in WHERE and choosing columns.
  3. Frozen Accounts List the frozen bank accounts with their balances. A first query on the Bank data.
  4. Heavy Courses List the courses worth at least 4 credits, sorted by code. Practice comparison operators on the School data.
  5. Orders in March 2025 Find the orders placed in March 2025. Practice date ranges on text dates.
  6. Orders Still in Progress Find the orders that are neither cancelled nor delivered. Practice NOT IN and combining conditions.
  7. Customers Without a Phone Number Find customers with no phone number. Practice IS NULL, because NULL never equals anything.
  8. Last Names Starting with S Find customers whose last name starts with S. Practice LIKE patterns and case.
  9. Open Accounts: Savings or Rich Find open accounts that are savings accounts or hold a lot of money. Practice AND, OR and brackets.
  10. The Five Lowest Grades Find the five lowest recorded grades. Practice NULL handling together with ORDER BY and LIMIT.
  11. Countries We Serve List each customer country once, in alphabetical order. Practice DISTINCT.
  12. Products, Page Two Return the second page of a product list: skip ten rows, take ten. Practice LIMIT and OFFSET with a stable order.
  13. Account Tiers Label accounts as low, medium or high by balance. Practice CASE expressions.

2. Functions, Dates and Cleaning

  1. Clean City Names The same city is typed in different cases. Return the distinct city names in lower case. Practice LOWER and DISTINCT.
  2. Email Usernames Cut the part before the @ out of an email address. Practice INSTR and SUBSTR.
  3. Full Names Build a full name from two columns with the || operator and an alias. Practice string concatenation.
  4. Twenty Percent Off Compute a discounted price rounded to two decimals. Practice arithmetic and ROUND.
  5. Cents to Dollars Show balances stored in cents as amounts with two decimals. Practice the integer division trap.
  6. Highest Margins Compute each product's profit margin in percent and list the five best. Practice calculated columns with ROUND.
  7. Sunday Orders Find orders placed on a Sunday in January 2026. Practice STRFTIME and weekday numbers.
  8. Days to Ship Compute how many days passed between ordering and shipping. Practice JULIANDAY and date arithmetic.
  9. Exact Age Compute a customer's exact age on a given date, taking the birthday into account. Practice date parts and boolean arithmetic.
  10. Unknown Guardian Show 'unknown' where a guardian name is missing. Practice COALESCE with NULL.
  11. Student Initials Build two-letter initials from a first and a last name. Practice SUBSTR and UPPER.
  12. Joined in the Last Quarter Find customers who joined between October and December 2025. Practice date ranges and month extraction.
  13. Long Email Addresses Find the longest email addresses. Practice LENGTH in WHERE and ORDER BY.

3. Aggregation and Grouping

  1. Customers per Country Count the customers in each country, largest group first. Practice COUNT with GROUP BY.
  2. Orders and Buyers Count all orders and the number of different customers who placed them. Practice COUNT(*) versus COUNT(DISTINCT).
  3. Balances of Open Accounts Summarise the balances of open accounts with SUM, AVG, MIN and MAX. Practice basic aggregate functions.
  4. Best-Selling Products Find the five products with the most units sold. Practice SUM per group with ordering.
  5. Frequent Buyers List customers with at least eight orders. Practice HAVING to filter groups.
  6. Graded versus Enrolled For the first five sections, compare how many students are enrolled with how many have a grade, and the average grade. Practice COUNT(column) and AVG with NULL.
  7. Transactions by Kind Count and total the transactions of each kind. Practice several aggregates in one grouped query.
  8. Monthly Deposits in 2025 Total the deposits of each month of 2025. Practice grouping by a date part.
  9. Order Status Pivot Turn order statuses into columns with conditional aggregation. Practice SUM(CASE ...) to pivot rows into columns.
  10. Attendance Rate Compute each section's attendance rate for the first six sections. Practice conditional aggregation for a percentage.
  11. Cities with Many Customers Count customers per city after cleaning the city names, and keep cities with more than 25 customers. Practice GROUP BY on an expression and HAVING.
  12. Accounts by Branch and Status Count accounts for every combination of branch and status. Practice grouping by two columns.
  13. Well-Reviewed Products Rank products by average rating, but only those with at least ten reviews. Practice HAVING with an AVG and a minimum sample size.
  14. Students with the Most Absences Find the three students with the most absences, with ties broken by student id. Practice filtering, grouping and a complete sort order.
  15. Largest Withdrawal per Account Find the five accounts with the largest single withdrawal. Practice MAX per group and filtering rows before grouping.

4. Joins

  1. Orders with Customer Names Show each order together with the name of its customer. Practice a first INNER JOIN.
  2. Products with Category and Supplier Join a product to its category and its supplier in one query. Practice joining three tables.
  3. Revenue per Category Compute the revenue of each product category from the order lines. Practice a three-table join with SUM and GROUP BY.
  4. Customers Who Never Ordered Find customers with no orders. Practice LEFT JOIN with IS NULL (an anti-join).
  5. Orders Never Paid List the orders that have no payment, by status. Practice an anti-join and counting groups.
  6. Employees and Their Managers List every employee with the name of their manager, including the top manager who has none. Practice a self join with LEFT JOIN.
  7. Subcategories and Their Parents Show each category that has a parent together with the parent's name. Practice a self join on a tree table.
  8. Accounts with Owner and Branch Show accounts with the owner's name and the branch name. Practice joining two parent tables to one child table.
  9. Customers Without Accounts Find bank customers who have no account. Practice an anti-join with NOT EXISTS.
  10. Balance per Branch Total the balances of open accounts for each branch. Practice a join with grouping and a filter.
  11. Accounts per Customer, Zeros Included Count the accounts of customers 1 to 12, showing 0 for customers with none. Practice LEFT JOIN with COUNT(column).
  12. Who Sent to Whom Show the sender and receiver names of transfers by joining the same tables twice. Practice multiple joins to the same table.
  13. The Fan-Out Trap Compare an order's item total with its payment without double counting. Practice aggregating each table before joining.
  14. Countries We Touch List every country that has a customer or a supplier, once each. Practice UNION.
  15. Offered Before but Not Later Find courses taught in 2025-Spring but not in 2026-Spring. Practice EXCEPT.
  16. Students with the Most Late Submissions Count each student's late submissions by comparing a submission date with the assignment's due date. Practice a join with a condition between two tables.

5. Subqueries and CTEs

  1. Above the Average Price List the products that cost more than the average product. Practice a scalar subquery in WHERE.
  2. Customers with Both Account Types Find customers who have at least one checking and at least one savings account. Practice two EXISTS conditions.
  3. Students Taking Biology List the students enrolled in any section of the course SCI301. Practice IN with a subquery.
  4. Latest Order of Each Customer Find the most recent order of each of the first six customers, breaking date ties by order id. Practice a correlated subquery.
  5. Average Enrollments per Student Compute the average number of enrollments per enrolled student. Practice aggregating an aggregate with a derived table.
  6. Customers Above the Average Spender Find the five customers whose total spending is above the average spending of customers. Practice chained CTEs.
  7. Accounts with Many Transactions Find accounts with more transactions than the average account. Practice a CTE reused in a comparison.
  8. Last Order Cancelled Find customers whose most recent order was cancelled. Practice combining 'latest per group' with a condition.
  9. Orders Above the Customer's Own Average Find orders whose total is higher than the average order total of the same customer. Practice a CTE with a correlated subquery.
  10. Category Paths Build the full path of every category, like 'Home > Kitchen', from the parent links. Practice a recursive CTE on a tree.
  11. Days Without Orders List the days of January 2024 that had no orders. Practice generating a calendar with a recursive CTE and a LEFT JOIN.
  12. Department Share of Courses Show each department's number of courses and its percentage of all courses. Practice a scalar subquery inside the select list.

6. Window Functions

  1. Price Rank in Category Rank the products of two categories by price inside each category. Practice RANK with PARTITION BY.
  2. Latest Order, the Window Way Get each customer's most recent order with ROW_NUMBER, breaking ties by order id. Practice the number-then-filter pattern.
  3. Top Three Products per Category List the three most expensive products of each category. Practice top N per group with ROW_NUMBER.
  4. Running Balance Rebuild an account's balance after each transaction with a running total. Practice SUM OVER with a signed amount.
  5. Month-over-Month Change Compare each month's deposits in 2025 with the previous month. Practice LAG.
  6. Grade Quartiles Split the graded students of one section into four equal groups by grade. Practice NTILE.
  7. Moving Average of Deposits Smooth the monthly deposits of 2025 with a 3-month moving average. Practice window frames.
  8. Second-Highest Grade per Section Find the second-highest distinct grade in five sections. Practice DENSE_RANK, a classic interview question.
  9. Days Between Orders Compute the days since the previous order for each of the first three customers. Practice LAG with PARTITION BY and date arithmetic.
  10. Most Active Customers, Ties Kept Rank customers by number of orders and keep everyone in the top three ranks. Practice RANK versus ROW_NUMBER with real ties.
  11. Rating Drops Find the reviews of product 11 that rated lower than the review before them. Practice LAG and filtering on a window result.
  12. Price versus the Category Maximum Show each product's price as a percentage of the most expensive product in its own category. Practice MAX OVER PARTITION BY.

7. Business Analytics

  1. Monthly Revenue and Growth Compute the revenue of each month of 2025 and its growth against the previous month. Combine joins, grouping and LAG.
  2. First-Order Cohorts Group customers by the month of their first order and measure how many came back. Practice cohort analysis with a CTE.
  3. Repeat Purchase Rate Compute the share of ordering customers who ordered more than once. A single-row KPI with a derived table.
  4. Which Products Make Half the Revenue Find the smallest set of top products that together make at least half of all revenue. Practice running totals and a cumulative percentage.
  5. Payment Mix by Year Show each year's share of payments by method as columns. Practice conditional aggregation for a pivot with percentages.
  6. Shipping Speed by City Compare the average days to ship across cities after cleaning the city names. Combine cleaning, date arithmetic, grouping and HAVING.
  7. Customer Activity Segments Segment customers by how recently they ordered, as of a fixed date. Practice date arithmetic, CASE and two-level aggregation.
  8. Dormant Open Accounts Find open accounts with no transactions in 2026. Practice an anti-join with a date condition inside the join.
  9. Loan Repayment Status Show the payments made on every loan that is not paid off, including loans with no payment. Practice LEFT JOIN, COALESCE and grouping.
  10. Net Transfer Flow Compute every account's net money received minus sent through completed transfers. Practice UNION ALL to treat two columns as one.
  11. Gradebook Percentages Compute each student's overall percentage over graded submissions and list the top five with enough work. Practice joins, weighted sums and HAVING.
  12. Teacher Reach Count the different students each teacher teaches and list the top five. Practice a three-table join with COUNT(DISTINCT).
  13. Customer Funnel Count how many customers reach each stage: registered, ordered, received an order and reviewed a product. Practice EXISTS for funnel stages.
  14. Frozen Account Share by Branch Compute the percentage of frozen accounts in each branch. Combine a join, conditional aggregation and ordering.

8. Interview Puzzles

  1. Median Product Price Compute the median price of all products without a MEDIAN function. Practice ROW_NUMBER, COUNT OVER and the odd/even rule.
  2. Duplicate Customers Find customers who appear more than once under the same name, ignoring case. Practice GROUP BY on cleaned text and HAVING.
  3. Same City, Same Day Find pairs of customers from the same city who joined on the same day. Practice a self join with a < condition to avoid mirrored pairs.
  4. Streaks of Active Months Find the runs of consecutive months in which an account had transactions. Practice the gaps-and-islands technique.
  5. Customers Who Bought from Every Category Find customers who bought at least one product from every category that has products. Practice relational division.
  6. Courses and Teachers Never Used List courses with no sections and teachers with no sections in one result with a label. Practice anti-joins combined with UNION ALL.
  7. Grade Bands per Section Count how many students fall into each grade band in five sections, as columns. Practice conditional aggregation with ranges.
  8. Best Seller per Category Find the product with the most units sold in each category, keeping ties. Practice joins, grouping and RANK.
  9. Team Size under Each Manager Count everyone below each manager, directly or indirectly. Practice a recursive CTE that carries the root of each branch.
  10. Longest Gap Between Orders Find the longest pause between consecutive orders for customers 1 to 12 who ordered at least twice. Practice LAG, MAX and a filter on groups.
  11. Year-over-Year Revenue by Category Compare each category's revenue in 2025 and 2026 and compute the growth. Practice conditional aggregation across years with joins.
  12. Top Spender in Each Country Find the highest-spending customer in each country. Combine joins, aggregation and a window function for top one per group.

9. Changing Data

  1. Add a Customer Insert one new customer with the required columns. Practice INSERT with named columns.
  2. Raise Prices in One Category Raise the prices of one category by 10 percent without touching the others. Practice UPDATE with WHERE and ROUND.
  3. Delete Old One-Star Reviews Delete one-star reviews written before 2025 and nothing else. Practice DELETE with two conditions.
  4. Freeze Small Open Accounts Freeze open accounts with a very small balance and leave closed accounts alone. Practice UPDATE with a status condition.
  5. Move Money Between Accounts Transfer 5,000 cents from one account to another so that the total stays the same. Practice a transaction with two updates.
  6. Load a Price List with an Upsert Insert a new product and update an existing one in the same statement without losing its stock. Practice INSERT ... ON CONFLICT DO UPDATE.
  7. Standardise City Names Fix inconsistent city spelling in place: first letter upper case, the rest lower case. Practice UPDATE with string functions.
  8. Remove Lines of Cancelled Orders Delete the order lines that belong to cancelled orders, using a subquery, and keep the orders themselves. Practice DELETE with IN (subquery) and foreign keys.
  9. Delete Customers with No Activity Delete customers who have no orders and no reviews, and nobody else. Practice DELETE with two NOT EXISTS conditions.
  10. Copy Low Grades to a New Table Create a table and fill it from a query in one statement. Practice CREATE TABLE AS SELECT.
  11. Design a Wishlist Table Create a wishlist table with a composite primary key and two foreign keys. Practice CREATE TABLE with constraints.