SQL practice · beginner to advanced

20 solved SQL exercises

Practise from SELECT to window functions with a downloadable database, explained solutions and results you can check in the editor.

Updated: September 27, 2026Worked examples
In this guide

How to practise with these exercises

These twenty solved SQL exercises progress from filters to queries with JOIN, grouping, subqueries, CTEs and window functions. They all use the site's fictional StoreSQL and have been run against the downloadable SQLite file. Attempt each challenge before opening its solution, compare the rows returned and then change the query.

Open the SQL Editor to run the queries in your browser. You can also download the SQLite database and use it on your own computer. The editor loads the same teaching database, and you do not need an account.

SQL exercises with solutions

We will use four tables: customers (id, name, city, active), products (id, name, price, stock), orders (id, customer_id, status, total) and order_items (order_id, product_id, quantity). Challenges 17 and 19 also use employees (id, name, department, salary, manager_id). Each expected result matches the current version of StoreSQL.

1. Filter active customers in London

Practice

Challenge 1

Not started

Show the name and city of active customers in London, sorted by name.

Expected result: 3 rows with the columns name, city, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Beginner · SELECT and WHERE

Your challenge

Show the name and city of active customers in London, sorted by name. In this database, active = 1 means the customer is active.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 1
SELECT name, city
FROM customers
WHERE active = 1 AND city = 'London'
ORDER BY name;

Verified result: 3 rows: Amy Wilson, Megan Reed and Nia Smith (all from London).

Filter the rows first, then sort the ones that meet both conditions. Without ORDER BY, the order is not guaranteed.

Try a variation: Replace London with Manchester and check how many active customers there are.

2. Find products with low stock

Practice

Challenge 2

Not started

Show the name and stock of products with stock below 10, sorted by stock and then name.

Expected result: 6 rows with the columns name, stock, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Beginner · filters and sorting

Your challenge

List name and stock for products with fewer than 10 units. Sort by stock ascending first, then by name.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 2
SELECT name, stock
FROM products
WHERE stock < 10
ORDER BY stock ASC, name ASC;

Verified result: 6 rows. The first two are Speaker and Pro Laptop, both with a stock of 0; the last one is SSD Drive with 9.

The second criterion breaks the tie between the zero-stock products. The filter < 10 also includes zero.

Try a variation: Change the threshold to stock <= 4 and predict which products remain.

3. List the distinct cities

Practice

Challenge 3

Not started

List the distinct customer cities in alphabetical order.

Expected result: 6 rows with the column city, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Beginner · DISTINCT

Your challenge

Get an alphabetical list of customer cities without duplicates. Return only the column city.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 3
SELECT DISTINCT city
FROM customers
ORDER BY city;

Verified result: 6 cities: Edinburgh, Bristol, London, Leeds, Manchester and Birmingham.

DISTINCT removes repeated values in the selected column; it does not count customers. To count cities, wrap this idea in COUNT(DISTINCT city).

Try a variation: Write a query that returns only the number of distinct cities.

4. Show the three most expensive products

Practice

Challenge 4

Not started

Show the name and price of the three most expensive products. Break ties by ascending id.

Expected result: 3 rows with the columns name, price, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Beginner · ORDER BY and LIMIT

Your challenge

Return the name and price of the three highest-priced products. Use id to break ties between equal prices.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 4
SELECT name, price
FROM products
ORDER BY price DESC, id
LIMIT 3;

Verified result: Pro Laptop (999), Monitor 27 (249) and Monitor 24 (179), in that order.

DESC puts the highest price first. In SQLite, LIMIT 3 keeps three rows; SQL Server would use TOP (3).

Try a variation: Show the three cheapest products by reversing the sort order.

5. Summarise orders by status

Practice

Challenge 5

Not started

Show status and COUNT(*) as the number of orders. Sort by the count descending, then status ascending.

Expected result: 3 rows with the columns status, quantity, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Intermediate · GROUP BY

Your challenge

Count how many orders there are in each status. Sort by the count descending and, for ties, by status name.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 5
SELECT status, COUNT(*) AS quantity
FROM orders
GROUP BY status
ORDER BY COUNT(*) DESC, status;

Verified result: shipped: 9; pending: 6; cancelled: 3.

Each group gathers the orders that share a status. COUNT(*) counts the rows in each group, and the sort compares group sizes.

Try a variation: Filter with HAVING COUNT(*) >= 6 before sorting.

6. Summarise orders and amounts per customer

Practice

Challenge 6

Not started

Show the customer name, COUNT(p.id) as orders and ROUND(SUM(p.total),2) as total. Include every status and keep the three customers with the highest total, using customer id as the tiebreaker.

Expected result: 3 rows with the columns name, orders, total, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Intermediate · INNER JOIN and SUM

Your challenge

Show the three customers with the highest sum of orders.total, without excluding any status. Return the name, the number of orders and the total rounded to two decimal places.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 6
SELECT c.name,
       COUNT(p.id) AS orders,
       ROUND(SUM(p.total), 2) AS total
FROM customers AS c
JOIN orders AS p ON p.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY SUM(p.total) DESC, c.id
LIMIT 3;

Verified result: Megan Reed: 3 orders and 1214.90; Sara Green: 2 and 1112.00; Amy Wilson: 3 and 402.30.

The JOIN links each order to its customer; grouping by id avoids merging people who might share a name. Every status is included, cancelled orders too, so this amount is not the money really received. The editor may show 1214.9: it is the same number as 1214.90; ROUND does not control how the number is displayed.

Try a variation: Add WHERE p.status != 'cancelled' before GROUP BY and watch what changes.

7. Find customers without orders

Practice

Challenge 7

Not started

Show the names of customers with no orders at all, sorted by name.

Expected result: 2 rows with the column name, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Intermediate · LEFT JOIN

Your challenge

Return the names of customers who have no row at all in orders, in alphabetical order.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 7
SELECT c.name
FROM customers AS c
LEFT JOIN orders AS p ON p.customer_id = c.id
WHERE p.id IS NULL
ORDER BY c.name;

Verified result: 2 rows: Miles Lee and Peter Hill.

The LEFT JOIN keeps every customer. When there is no matching order, the columns from p are NULL; the filter selects those cases.

Try a variation: Solve the same challenge with NOT EXISTS and compare the results.

8. Count units per product in orders

Practice

Challenge 8

Not started

Show the product name and SUM(quantity) as units from order_items. Include every order status and the three highest counts, using product id as the tiebreaker.

Expected result: 3 rows with the columns name, units, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Intermediate · JOIN and aggregation

Your challenge

Sum order_items.quantity for each product and show the three with the most units. For ties, sort by product id.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 8
SELECT pr.name, SUM(d.quantity) AS units
FROM products AS pr
JOIN order_items AS d ON d.product_id = pr.id
GROUP BY pr.id, pr.name
ORDER BY SUM(d.quantity) DESC, pr.id
LIMIT 3;

Verified result: Cable USB-C: 6 units; Mouse: 4; Headphones: 4.

The question asks about units, which is why we use SUM(quantity) instead of COUNT(*). Lines from cancelled orders are included here because the table has not been joined or filtered: orders.

Try a variation: Also join orders and exclude cancelled orders; explain why the ranking changes.

9. Find customers with no email

Practice

Challenge 9

Not started

Show the name and city of customers with no email address, sorted by name.

Expected result: 3 rows with the columns name, city, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Beginner · NULL

Your challenge

Show name and city of customers with no email address on record, sorted by name.

Before running: predict how many rows your query will return.

See solution and expected result
Exercise 9 solution
SELECT name, city
FROM customers
WHERE email IS NULL
ORDER BY name;

Verified result: Three rows: David Clark (Bristol), Miles Lee (Edinburgh) and Peter Hill (London).

email = NULL is never true, because comparing with an unknown value gives an unknown result. That is why the correct condition is IS NULL.

Try a variation: Change the condition to IS NOT NULL and check that you get the other nine rows.

10. Search products by text pattern

Practice

Challenge 10

Not started

Show the name and price of products whose name starts with Monitor, sorted by price ascending.

Expected result: 2 rows with the columns name, price, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Beginner · LIKE

Your challenge

Show name and price of products whose name starts with “Monitor”, from cheapest to most expensive.

Before running: predict how many rows your query will return.

See solution and expected result
Exercise 10 solution
SELECT name, price
FROM products
WHERE name LIKE 'Monitor%'
ORDER BY price;

Verified result: Monitor 24 at 179.00 and Monitor 27 at 249.00.

The pattern 'Monitor%' requires the text to start with “Monitor” and accepts anything after it. With '%Monitor%' names containing it in the middle would also match.

Try a variation: Find the products whose name contains the letter “o” with LIKE '%o%' and count how many you get.

11. Filter orders between two dates

Practice

Challenge 11

Not started

Show the id, date and total of orders between 2025-06-01 and 2025-06-10, both included, sorted by date.

Expected result: 5 rows with the columns id, date, total, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Beginner · BETWEEN

Your challenge

Show id, date and total of orders placed between 1 and 10 June 2025, both included, by date.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 11
SELECT id, date, total
FROM orders
WHERE date BETWEEN '2025-06-01' AND '2025-06-10'
ORDER BY date;

Verified result: Five orders, from 111 to 115. Order 115, from the 10th, is included because BETWEEN includes both ends.

BETWEEN includes both ends, which is why the order from the 10th is included. If the column also stored the time, an order placed on the afternoon of the 10th would be left out: in that case use date < '2025-06-11'.

Try a variation: Rewrite the filter with >= and < and check that the result is the same.

12. Choose products from several categories

Practice

Challenge 12

Not started

Show the name, category and price of products in the Audio or Displays categories, sorted by category and price.

Expected result: 4 rows with the columns name, category, price, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Beginner · IN

Your challenge

Show name, category and price of products in the Audio or Displays categories, sorted by category and price.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 12
SELECT name, category, price
FROM products
WHERE category IN ('Audio', 'Displays')
ORDER BY category, price;

Verified result: Speaker (54.00) and Headphones (69.90) in Audio; Monitor 24 (179.00) and Monitor 27 (249.00) in Displays.

IN ('Audio', 'Displays') is equivalent to category = 'Audio' OR category = 'Displays', but it reads better and does not force you to add parentheses when you combine it with another condition using AND.

Try a variation: Add AND stock > 0 and see which product disappears.

13. Classify stock with CASE

Practice

Challenge 13

Not started

Show name, stock and a level column: 'out_of_stock' if stock is 0, 'low' if it is below 10 and 'sufficient' otherwise. Sort by stock and name.

Expected result: 9 rows with the columns name, stock, level, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Intermediate · CASE

Your challenge

Show name, stock and a column level that is 'out_of_stock' when stock is 0, 'low' when it is below 10 and 'sufficient' otherwise. Sort by stock and name.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 13
SELECT name, stock,
       CASE
         WHEN stock = 0 THEN 'out_of_stock'
         WHEN stock < 10 THEN 'low'
         ELSE 'sufficient'
       END AS level
FROM products
ORDER BY stock, name;

Verified result: Two products out of stock (Speaker and Pro Laptop), four with low stock and three with enough stock.

CASE checks the conditions in order and keeps the first one that is true. If you put stock < 10first, the out-of-stock products would come out as 'low'.

Try a variation: Count how many products there are at each level with GROUP BY on the same expression.

14. Find the most frequent customers

Practice

Challenge 14

Not started

Show name and COUNT(p.id) as orders for customers with at least three orders, sorted by name.

Expected result: 2 rows with the columns name, orders, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Intermediate · HAVING

Your challenge

Show the name of customers with at least three orders and how many orders they have (orders), sorted by name.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 14
SELECT c.name, COUNT(p.id) AS orders
FROM customers AS c
JOIN orders AS p ON p.customer_id = c.id
GROUP BY c.id, c.name
HAVING COUNT(p.id) >= 3
ORDER BY c.name;

Verified result: Amy Wilson and Megan Reed, with three orders each.

WHERE filters rows before grouping and cannot use COUNT; HAVING filters the groups once they are formed. Orders with any status are counted, including cancelled ones.

Try a variation: Exclude cancelled orders with a WHERE before grouping and check who drops out.

15. Compare with the average using a subquery

Practice

Challenge 15

Not started

Show the name and price of products that cost more than the average price of all products, sorted by price descending.

Expected result: 2 rows with the columns name, price, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Intermediate · Subquery

Your challenge

Show name and price of products whose price is above the average price of all products, from most expensive to cheapest.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 15
SELECT name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products)
ORDER BY price DESC;

Verified result: Pro Laptop at 999.00 and Monitor 27 at 249.00.

The subquery returns a single value (about 191.81), so it can be compared with >. You cannot write WHERE price > AVG(price) directly, because WHERE does not accept aggregate functions.

Try a variation: Also show the average on every row by adding the subquery to the SELECT with the alias average.

16. Summarise orders by month

Practice

Challenge 16

Not started

Show strftime('%Y-%m', date) as month, COUNT(*) as orders and ROUND(SUM(total), 2) as total, grouped and sorted by month.

Expected result: 2 rows with the columns month, orders, total, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Intermediate · Dates

Your challenge

Show each month (month, in YYYY-MM format), how many orders there were (orders) and the sum of their order amounts rounded to two decimal places (total), sorted by month.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 16
SELECT strftime('%Y-%m', date) AS month,
       COUNT(*) AS orders,
       ROUND(SUM(total), 2) AS total
FROM orders
GROUP BY month
ORDER BY month;

Verified result: 2025-05: 10 orders and 1,976.10 in all; 2025-06: 8 orders and 1,955.80.

strftime is specific to SQLite; in PostgreSQL you would use to_char(date, 'YYYY-MM') or date_trunc, and in MySQL DATE_FORMAT(date, '%Y-%m'). The sum includes cancelled orders, so it is not real revenue.

Try a variation: Add WHERE status = 'shipped' and compare the amount for each month.

17. Join a table to itself

Practice

Challenge 17

Not started

Show e.name as employee and r.name as manager for employees who have a manager, sorted by employee.

Expected result: 9 rows with the columns employee, manager, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Intermediate · Self JOIN

Your challenge

Show each employee (employee) next to the name of their direct manager (manager). Leave out anyone without a manager and sort by employee.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 17
SELECT e.name AS employee, r.name AS manager
FROM employees AS e
JOIN employees AS r ON r.id = e.manager_id
ORDER BY e.name;

Verified result: Nine rows: everyone except Claire Smith, who has no manager.

Aliases let you treat the same table as if it were two. With JOIN the director disappears, because her manager_id is NULL; with LEFT JOIN she would appear with an empty manager.

Try a variation: Switch to LEFT JOIN and check which new row appears.

18. Count active and inactive customers by city

Practice

Challenge 18

Not started

Show city, SUM(CASE WHEN active = 1 THEN 1 ELSE 0 END) as active and the equivalent sum for active = 0 as inactive, grouped and sorted by city.

Expected result: 6 rows with the columns city, active, inactive, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Intermediate · Conditional aggregation

Your challenge

For each city, show how many active (active) and inactive (inactive) customers it has, sorted by city.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 18
SELECT city,
       SUM(CASE WHEN active = 1 THEN 1 ELSE 0 END) AS active,
       SUM(CASE WHEN active = 0 THEN 1 ELSE 0 END) AS inactive
FROM customers
GROUP BY city
ORDER BY city;

Verified result: Six cities; only London has an inactive customer (three active and one inactive).

This technique is called conditional aggregation: it turns rows into columns without running several queries. PostgreSQL also offers COUNT(*) FILTER (WHERE active = 1).

Try a variation: Add a third column with COUNT(*) and check that it always equals active + inactive.

19. Find the highest salary in each department

Practice

Challenge 19

Not started

Use ROW_NUMBER() per department, ordered by salary descending, and show department, name and salary for row number 1 of each department, sorted by department.

Expected result: 5 rows with the columns department, name, salary, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Advanced · Window functions

Your challenge

Show department, name and salary of the person with the highest salary in each department, sorted by department.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 19
WITH ranking AS (
  SELECT department, name, salary,
         ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS n
  FROM employees
)
SELECT department, name, salary
FROM ranking
WHERE n = 1
ORDER BY department;

Verified result: Five rows: Claire Smith in Management, Graham Newton in Marketing, Faith Rivers in Support, Charles Page in Technology and Isaac Davis in Sales.

You cannot filter on a window function in the same WHERE where it is calculated, which is why the numbering goes in a CTE. If two people had the same salary, ROW_NUMBER would pick only one; RANK would keep both.

Try a variation: Change n = 1 by n <= 2 to see the two highest salaries in each department.

20. Work out spending per customer with a CTE

Practice

Challenge 20

Not started

With a CTE, add up the total of each customer's shipped orders and show name and ROUND(spending, 2) as spent for those above 200, sorted by spent descending.

Expected result: 2 rows with the columns name, spent, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Advanced · CTE

Your challenge

Show the name of customers whose spending on shipped orders is above 200, and that spending rounded to two decimal places (spent), from highest to lowest.

Before running: predict how many rows your query will return.

See solution and expected result
Solution to exercise 20
WITH spending AS (
  SELECT customer_id, SUM(total) AS spent
  FROM orders
  WHERE status = 'shipped'
  GROUP BY customer_id
)
SELECT c.name, ROUND(g.spent, 2) AS spent
FROM spending AS g
JOIN customers AS c ON c.id = g.customer_id
WHERE g.spent > 200
ORDER BY g.spent DESC;

Verified result: Sara Green with 1,112.00 and Megan Reed with 215.90.

The CTE separates the calculation from the final filter and makes the query easier to read and to check step by step. You can get the same result with GROUP BY and HAVING, but this way you can run just the CTE first to check the amounts.

Try a variation: Run only the SELECT of the CTE and check each customer's spending before the filter.

More solved SQL exercises by topic

These 20 challenges mix several topics. To practise one in particular, every lesson in the course includes interactive exercises checked in the same way: 139 in all, grouped by module.

To practise joins and summaries together, continue with the 10 solved JOIN and aggregation exercises. If you are preparing for an interview, go over the 20 SQL interview questions with answers.

Once you have solved them

If you got any of the first four wrong, review SELECT, WHERE and sorting and limits. For the later ones, practise GROUP BY, INNER JOIN and LEFT JOIN. Then try the sales analysis project without looking at the solutions.

The examples are written for SQLite. PostgreSQL and MySQL share most of this syntax; SQL Server changes LIMIT by TOP u OFFSET ... FETCH, depending on the query.