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
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.
There are two conditions and both must be true at once.
Combine active = 1 and city = 'London' with AND.
Finish with ORDER BY name.
Solution explained
SELECT name, city
FROM customers
WHERE active = 1 AND city = 'London'
ORDER BY name;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
Filter for stock below 10: a stock of exactly 10 is excluded.
Sort by stock and, for ties, by name.
WHERE stock < 10 ORDER BY stock ASC, name ASC.
Solution explained
SELECT name, stock
FROM products
WHERE stock < 10
ORDER BY stock ASC, name ASC;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
You need each city only once.
Write DISTINCT right after SELECT.
SELECT DISTINCT city FROM customers ORDER BY city.
Solution explained
SELECT DISTINCT city
FROM customers
ORDER BY city;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
Sort first, then limit.
Sort price from highest to lowest and use ascending id as the tiebreaker.
ORDER BY price DESC, id LIMIT 3.
Solution explained
SELECT name, price
FROM products
ORDER BY price DESC, id
LIMIT 3;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
Group orders by status and count them.
Use COUNT(*) AS quantity with GROUP BY status.
Sort by COUNT(*) DESC and, if tied, by status.
Solution explained
SELECT status, COUNT(*) AS quantity
FROM orders
GROUP BY status
ORDER BY COUNT(*) DESC, status;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
Each customer must be one row, so group by customer.
Join customers to orders, count with COUNT(p.id) and add up with ROUND(SUM(p.total), 2).
Sort by SUM(p.total) DESC, c.id and limit to 3 rows.
Solution explained
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;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
Look for customers who have no related row in orders.
Use LEFT JOIN and keep the rows where p.id IS NULL.
Sort by name at the end.
Solution explained
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;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
Units come from order_items.quantity.
Join products to order_items, group by product and add up SUM(d.quantity) AS units.
Sort by SUM(d.quantity) DESC, pr.id and limit to 3 rows.
Solution explained
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;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
A missing email is stored as NULL, not as empty text.
= NULL does not work with NULL: use IS NULL.
WHERE email IS NULL ORDER BY name.
Solution explained
SELECT name, city
FROM customers
WHERE email IS NULL
ORDER BY name;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
You need to search for a pattern in the text, not an exact value.
The % wildcard stands for any number of characters.
WHERE name LIKE 'Monitor%' ORDER BY price.
Solution explained
SELECT name, price
FROM products
WHERE name LIKE 'Monitor%'
ORDER BY price;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
Dates are stored as text in YYYY-MM-DD format, so they can be compared.
BETWEEN includes both ends of the range.
WHERE date BETWEEN '2025-06-01' AND '2025-06-10' ORDER BY date.
Solution explained
SELECT id, date, total
FROM orders
WHERE date BETWEEN '2025-06-01' AND '2025-06-10'
ORDER BY date;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
The category must match one of several values.
IN saves you from chaining several conditions with OR.
WHERE category IN ('Audio', 'Displays') ORDER BY category, price.
Solution explained
SELECT name, category, price
FROM products
WHERE category IN ('Audio', 'Displays')
ORDER BY category, price;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
CASE returns a different value depending on the first condition that is true.
Put the strictest condition first: stock = 0.
CASE WHEN stock = 0 THEN 'out_of_stock' WHEN stock < 10 THEN 'low' ELSE 'sufficient' END AS level.
Solution explained
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;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
First join customers to their orders and group by customer.
The filter applies to a count, so it goes in HAVING, not WHERE.
GROUP BY c.id, c.name HAVING COUNT(p.id) >= 3 ORDER BY c.name.
Solution explained
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;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
You need to work out the average before you can compare each product with it.
A subquery in parentheses can return that single value.
WHERE price > (SELECT AVG(price) FROM products) ORDER BY price DESC.
Solution explained
SELECT name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products)
ORDER BY price DESC;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
First extract the year and month from each date.
In SQLite, strftime('%Y-%m', date) returns text such as 2025-05.
Group by that expression and sort by month.
Solution explained
SELECT strftime('%Y-%m', date) AS month,
COUNT(*) AS orders,
ROUND(SUM(total), 2) AS total
FROM orders
GROUP BY month
ORDER BY month;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
The manager is also a row in the employees table.
Use the table twice with different aliases, for example e and r.
JOIN employees AS r ON r.id = e.manager_id ORDER BY e.name.
Solution explained
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;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
You need two different counts in the same row for each city.
A CASE that returns 1 or 0 inside SUM counts only the rows that meet the condition.
SUM(CASE WHEN active = 1 THEN 1 ELSE 0 END) AS active, and the same with active = 0.
Solution explained
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;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
Number the people within each department, from highest to lowest salary.
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) does that numbering.
Work out the numbering in a CTE and then filter WHERE n = 1.
Solution explained
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;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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
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.
First work out each customer's spending, counting only shipped orders.
That calculation can go in a CTE with WITH and then be joined to customers.
WITH spending AS (SELECT customer_id, SUM(total) AS spent FROM orders WHERE status = 'shipped' GROUP BY customer_id) ...
Solution explained
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;Check the filter, what each row represents and the order described in the task. This output follows the challenge rule exactly.
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
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.
- Orientation: 6 exercises
- Selecting data: 7 exercises
- Filtering data: 18 exercises
- Sorting and summarising: 14 exercises
- Relating tables: 11 exercises
- Advanced queries: 35 exercises
- Modifying data: 10 exercises
- Designing tables: 12 exercises
- Putting it together: 9 exercises
- Final project, reviews and placement test: 17 exercises
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.