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.
- Chapter 1 Select, Filter and Sort Read the right rows and columns in the right order: WHERE, NULL, LIKE, CASE, LIMIT. 13 problems
- Chapter 2 Functions, Dates and Cleaning Turn messy real-world columns into clean answers: text, numbers, dates and missing values. 13 problems
- 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
- 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
- Chapter 5 Subqueries and CTEs Break a hard question into steps: scalar and correlated subqueries, EXISTS, derived tables, WITH and recursion. 12 problems
- 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
- Chapter 7 Business Analytics Answer the questions managers really ask: growth, cohorts, funnels, segments and concentration. Each problem combines several skills. 14 problems
- 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
- 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
- Expensive Products List the products that cost more than 50, most expensive first. Practice WHERE and ORDER BY on the Shop data.
- Customers from Egypt Find the customers whose country is Egypt. Practice a text comparison in WHERE and choosing columns.
- Frozen Accounts List the frozen bank accounts with their balances. A first query on the Bank data.
- Heavy Courses List the courses worth at least 4 credits, sorted by code. Practice comparison operators on the School data.
- Orders in March 2025 Find the orders placed in March 2025. Practice date ranges on text dates.
- Orders Still in Progress Find the orders that are neither cancelled nor delivered. Practice NOT IN and combining conditions.
- Customers Without a Phone Number Find customers with no phone number. Practice IS NULL, because NULL never equals anything.
- Last Names Starting with S Find customers whose last name starts with S. Practice LIKE patterns and case.
- Open Accounts: Savings or Rich Find open accounts that are savings accounts or hold a lot of money. Practice AND, OR and brackets.
- The Five Lowest Grades Find the five lowest recorded grades. Practice NULL handling together with ORDER BY and LIMIT.
- Countries We Serve List each customer country once, in alphabetical order. Practice DISTINCT.
- Products, Page Two Return the second page of a product list: skip ten rows, take ten. Practice LIMIT and OFFSET with a stable order.
- Account Tiers Label accounts as low, medium or high by balance. Practice CASE expressions.
2. Functions, Dates and Cleaning
- Clean City Names The same city is typed in different cases. Return the distinct city names in lower case. Practice LOWER and DISTINCT.
- Email Usernames Cut the part before the @ out of an email address. Practice INSTR and SUBSTR.
- Full Names Build a full name from two columns with the || operator and an alias. Practice string concatenation.
- Twenty Percent Off Compute a discounted price rounded to two decimals. Practice arithmetic and ROUND.
- Cents to Dollars Show balances stored in cents as amounts with two decimals. Practice the integer division trap.
- Highest Margins Compute each product's profit margin in percent and list the five best. Practice calculated columns with ROUND.
- Sunday Orders Find orders placed on a Sunday in January 2026. Practice STRFTIME and weekday numbers.
- Days to Ship Compute how many days passed between ordering and shipping. Practice JULIANDAY and date arithmetic.
- Exact Age Compute a customer's exact age on a given date, taking the birthday into account. Practice date parts and boolean arithmetic.
- Unknown Guardian Show 'unknown' where a guardian name is missing. Practice COALESCE with NULL.
- Student Initials Build two-letter initials from a first and a last name. Practice SUBSTR and UPPER.
- Joined in the Last Quarter Find customers who joined between October and December 2025. Practice date ranges and month extraction.
- Long Email Addresses Find the longest email addresses. Practice LENGTH in WHERE and ORDER BY.
3. Aggregation and Grouping
- Customers per Country Count the customers in each country, largest group first. Practice COUNT with GROUP BY.
- Orders and Buyers Count all orders and the number of different customers who placed them. Practice COUNT(*) versus COUNT(DISTINCT).
- Balances of Open Accounts Summarise the balances of open accounts with SUM, AVG, MIN and MAX. Practice basic aggregate functions.
- Best-Selling Products Find the five products with the most units sold. Practice SUM per group with ordering.
- Frequent Buyers List customers with at least eight orders. Practice HAVING to filter groups.
- 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.
- Transactions by Kind Count and total the transactions of each kind. Practice several aggregates in one grouped query.
- Monthly Deposits in 2025 Total the deposits of each month of 2025. Practice grouping by a date part.
- Order Status Pivot Turn order statuses into columns with conditional aggregation. Practice SUM(CASE ...) to pivot rows into columns.
- Attendance Rate Compute each section's attendance rate for the first six sections. Practice conditional aggregation for a percentage.
- 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.
- Accounts by Branch and Status Count accounts for every combination of branch and status. Practice grouping by two columns.
- 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.
- 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.
- Largest Withdrawal per Account Find the five accounts with the largest single withdrawal. Practice MAX per group and filtering rows before grouping.
4. Joins
- Orders with Customer Names Show each order together with the name of its customer. Practice a first INNER JOIN.
- Products with Category and Supplier Join a product to its category and its supplier in one query. Practice joining three tables.
- Revenue per Category Compute the revenue of each product category from the order lines. Practice a three-table join with SUM and GROUP BY.
- Customers Who Never Ordered Find customers with no orders. Practice LEFT JOIN with IS NULL (an anti-join).
- Orders Never Paid List the orders that have no payment, by status. Practice an anti-join and counting groups.
- 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.
- 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.
- 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.
- Customers Without Accounts Find bank customers who have no account. Practice an anti-join with NOT EXISTS.
- Balance per Branch Total the balances of open accounts for each branch. Practice a join with grouping and a filter.
- 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).
- 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.
- The Fan-Out Trap Compare an order's item total with its payment without double counting. Practice aggregating each table before joining.
- Countries We Touch List every country that has a customer or a supplier, once each. Practice UNION.
- Offered Before but Not Later Find courses taught in 2025-Spring but not in 2026-Spring. Practice EXCEPT.
- 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
- Above the Average Price List the products that cost more than the average product. Practice a scalar subquery in WHERE.
- Customers with Both Account Types Find customers who have at least one checking and at least one savings account. Practice two EXISTS conditions.
- Students Taking Biology List the students enrolled in any section of the course SCI301. Practice IN with a subquery.
- 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.
- Average Enrollments per Student Compute the average number of enrollments per enrolled student. Practice aggregating an aggregate with a derived table.
- Customers Above the Average Spender Find the five customers whose total spending is above the average spending of customers. Practice chained CTEs.
- Accounts with Many Transactions Find accounts with more transactions than the average account. Practice a CTE reused in a comparison.
- Last Order Cancelled Find customers whose most recent order was cancelled. Practice combining 'latest per group' with a condition.
- 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.
- Category Paths Build the full path of every category, like 'Home > Kitchen', from the parent links. Practice a recursive CTE on a tree.
- 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.
- 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
- Price Rank in Category Rank the products of two categories by price inside each category. Practice RANK with PARTITION BY.
- 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.
- Top Three Products per Category List the three most expensive products of each category. Practice top N per group with ROW_NUMBER.
- Running Balance Rebuild an account's balance after each transaction with a running total. Practice SUM OVER with a signed amount.
- Month-over-Month Change Compare each month's deposits in 2025 with the previous month. Practice LAG.
- Grade Quartiles Split the graded students of one section into four equal groups by grade. Practice NTILE.
- Moving Average of Deposits Smooth the monthly deposits of 2025 with a 3-month moving average. Practice window frames.
- Second-Highest Grade per Section Find the second-highest distinct grade in five sections. Practice DENSE_RANK, a classic interview question.
- 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.
- 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.
- Rating Drops Find the reviews of product 11 that rated lower than the review before them. Practice LAG and filtering on a window result.
- 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
- Monthly Revenue and Growth Compute the revenue of each month of 2025 and its growth against the previous month. Combine joins, grouping and LAG.
- First-Order Cohorts Group customers by the month of their first order and measure how many came back. Practice cohort analysis with a CTE.
- Repeat Purchase Rate Compute the share of ordering customers who ordered more than once. A single-row KPI with a derived table.
- 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.
- Payment Mix by Year Show each year's share of payments by method as columns. Practice conditional aggregation for a pivot with percentages.
- Shipping Speed by City Compare the average days to ship across cities after cleaning the city names. Combine cleaning, date arithmetic, grouping and HAVING.
- Customer Activity Segments Segment customers by how recently they ordered, as of a fixed date. Practice date arithmetic, CASE and two-level aggregation.
- Dormant Open Accounts Find open accounts with no transactions in 2026. Practice an anti-join with a date condition inside the join.
- 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.
- Net Transfer Flow Compute every account's net money received minus sent through completed transfers. Practice UNION ALL to treat two columns as one.
- 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.
- Teacher Reach Count the different students each teacher teaches and list the top five. Practice a three-table join with COUNT(DISTINCT).
- Customer Funnel Count how many customers reach each stage: registered, ordered, received an order and reviewed a product. Practice EXISTS for funnel stages.
- Frozen Account Share by Branch Compute the percentage of frozen accounts in each branch. Combine a join, conditional aggregation and ordering.
8. Interview Puzzles
- Median Product Price Compute the median price of all products without a MEDIAN function. Practice ROW_NUMBER, COUNT OVER and the odd/even rule.
- Duplicate Customers Find customers who appear more than once under the same name, ignoring case. Practice GROUP BY on cleaned text and HAVING.
- 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.
- Streaks of Active Months Find the runs of consecutive months in which an account had transactions. Practice the gaps-and-islands technique.
- Customers Who Bought from Every Category Find customers who bought at least one product from every category that has products. Practice relational division.
- 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.
- Grade Bands per Section Count how many students fall into each grade band in five sections, as columns. Practice conditional aggregation with ranges.
- Best Seller per Category Find the product with the most units sold in each category, keeping ties. Practice joins, grouping and RANK.
- Team Size under Each Manager Count everyone below each manager, directly or indirectly. Practice a recursive CTE that carries the root of each branch.
- 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.
- 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.
- 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
- Add a Customer Insert one new customer with the required columns. Practice INSERT with named columns.
- Raise Prices in One Category Raise the prices of one category by 10 percent without touching the others. Practice UPDATE with WHERE and ROUND.
- Delete Old One-Star Reviews Delete one-star reviews written before 2025 and nothing else. Practice DELETE with two conditions.
- Freeze Small Open Accounts Freeze open accounts with a very small balance and leave closed accounts alone. Practice UPDATE with a status condition.
- 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.
- 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.
- Standardise City Names Fix inconsistent city spelling in place: first letter upper case, the rest lower case. Practice UPDATE with string functions.
- 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.
- Delete Customers with No Activity Delete customers who have no orders and no reviews, and nobody else. Practice DELETE with two NOT EXISTS conditions.
- Copy Low Grades to a New Table Create a table and fill it from a query in one statement. Practice CREATE TABLE AS SELECT.
- Design a Wishlist Table Create a wishlist table with a composite primary key and two foreign keys. Practice CREATE TABLE with constraints.