TExcelTAD
Home › MySQL › MySQL Exercises

MySQL Exercises

Time to practise on the shop database. Each exercise has a starter playground that already runs and does part of the job. Work out the missing parts (marked TODO), and compare your result with the expected answer. On this site the playgrounds show the starter's saved result; to run your own version, use a local MySQL or MariaDB server loaded with the sample database. Try for a few minutes before opening the solution.

# Exercise Topics
1 Mid-priced and well stocked WHERE, BETWEEN, AND, ORDER BY
2 Incomplete customer records IS NULL, OR, COALESCE
3 Countries with several customers GROUP BY, HAVING
4 One customer's order history INNER JOIN of three tables
5 Products per supplier LEFT JOIN, COUNT, AVG
6 The biggest delivered orders joins, SUM, LIMIT
7 Sales rep scoreboard LEFT JOIN, conditional counting
8 Slow shipments DATEDIFF
9 A price increase UPDATE with a subquery
10 Cheapest product per category window functions, CTE

1. Mid-priced and well stocked

List the name, unit_price and units_in_stock of products that cost between 2 and 5 (inclusive) and have at least 50 units in stock, most expensive first.

Expected: 5 rows, from Orange Juice 1L | 3.20 | 60 down to Dish Soap 500ml | 2.30 | 100.

mysql · try it yourself
-- TODO: add the stock condition and the sort order
SELECT name, unit_price, units_in_stock
FROM products
WHERE unit_price BETWEEN 2 AND 5;
+----------------------+------------+----------------+
| name                 | unit_price | units_in_stock |
+----------------------+------------+----------------+
| Orange Juice 1L      |       3.20 |             60 |
| Sparkling Water 6x1L |       4.99 |              0 |
| Sourdough Loaf       |       4.80 |             25 |
| Rye Crackers         |       2.90 |              0 |
| Greek Yogurt 500g    |       3.95 |             45 |
| Salted Butter 250g   |       2.85 |             70 |
| Gala Apples 1kg      |       2.99 |             90 |
| Cherry Tomatoes 500g |       2.75 |             35 |
| Dark Chocolate Bar   |       2.49 |             80 |
| Dish Soap 500ml      |       2.30 |            100 |
+----------------------+------------+----------------+
Show solution
sql
SELECT name, unit_price, units_in_stock
FROM products
WHERE unit_price BETWEEN 2 AND 5
  AND units_in_stock >= 50
ORDER BY unit_price DESC;

2. Incomplete customer records

Find customers with a missing e-mail or a missing city. Show customer (first and last name), city (or '(unknown)') and email (or '(none)'), sorted by last name.

Expected: 4 rows: George Brown, Mia Jensen, Chloe Martin and Ivan Petrov (the only one with an unknown city).

mysql · try it yourself
-- TODO: keep only incomplete records and replace the NULLs
SELECT CONCAT(first_name, ' ', last_name) AS customer, city, email
FROM customers
WHERE email IS NULL;
+--------------+--------+-------+
| customer     | city   | email |
+--------------+--------+-------+
| Chloe Martin | Paris  | NULL  |
| George Brown | London | NULL  |
| Mia Jensen   | Aarhus | NULL  |
+--------------+--------+-------+
Show solution
sql
SELECT CONCAT(first_name, ' ', last_name) AS customer,
       COALESCE(city, '(unknown)') AS city,
       COALESCE(email, '(none)') AS email
FROM customers
WHERE email IS NULL OR city IS NULL
ORDER BY last_name;

3. Countries with several customers

Which countries have two or more customers? Show country and customers, largest first, ties alphabetically.

Expected: UK | 3, then France and Germany with 2 each.

mysql · try it yourself
-- TODO: group by country and keep only the bigger groups
SELECT country, COUNT(*) AS customers
FROM customers
GROUP BY country
ORDER BY customers DESC, country
LIMIT 4;
+----------+-----------+
| country  | customers |
+----------+-----------+
| UK       |         3 |
| France   |         2 |
| Germany  |         2 |
| Bulgaria |         1 |
+----------+-----------+
Show solution
sql
SELECT country, COUNT(*) AS customers
FROM customers
GROUP BY country
HAVING COUNT(*) >= 2
ORDER BY customers DESC, country;

4. One customer's order history

List every order of Ben Carter: order id, order date, the first name of the employee who handled it (handled_by) and the status, oldest first. Find Ben by his name, not by his id.

Expected: orders 2 (Maya, delivered), 8 (Linus, cancelled) and 19 (Omar, shipped).

mysql · try it yourself
-- TODO: join customers and employees and filter by Ben's name
SELECT o.order_id, o.order_date, o.status
FROM orders AS o
WHERE o.customer_id = 2;
+----------+------------+-----------+
| order_id | order_date | status    |
+----------+------------+-----------+
|        2 | 2025-01-09 | delivered |
|        8 | 2025-02-22 | cancelled |
|       19 | 2025-05-20 | shipped   |
+----------+------------+-----------+
Show solution
sql
SELECT o.order_id, o.order_date, e.first_name AS handled_by, o.status
FROM orders AS o
JOIN customers AS c ON c.customer_id = o.customer_id
JOIN employees AS e ON e.employee_id = o.employee_id
WHERE c.first_name = 'Ben' AND c.last_name = 'Carter'
ORDER BY o.order_date;

5. Products per supplier

For every supplier show its name (supplier), the number of products (products) and their average price rounded to 2 decimals (avg_price). Most products first, ties by supplier name.

Expected: 6 rows, starting with Sunny Fields Farm | 5 | 3.04 and ending with Highland Roasters | 2 | 15.63.

mysql · try it yourself
-- TODO: join the products and aggregate per supplier
SELECT s.name AS supplier
FROM suppliers AS s
ORDER BY supplier;
+--------------------+
| supplier           |
+--------------------+
| Alpine Dairy Co    |
| CleanHome Supplies |
| Crunch & Co        |
| Golden Crust Ltd   |
| Highland Roasters  |
| Sunny Fields Farm  |
+--------------------+
Show solution
sql
SELECT s.name AS supplier,
       COUNT(p.product_id) AS products,
       ROUND(AVG(p.unit_price), 2) AS avg_price
FROM suppliers AS s
LEFT JOIN products AS p ON p.supplier_id = s.supplier_id
GROUP BY s.supplier_id, s.name
ORDER BY products DESC, supplier;

A LEFT JOIN with COUNT(p.product_id) would also list a supplier without products (with 0). Every supplier happens to have products here, so an inner join gives the same rows.

6. The biggest delivered orders

Show the three delivered orders with the highest total (quantity * unit_price * (1 - discount) summed over the lines, rounded to 2 decimals).

Expected: orders 4 (59.00), 15 (36.50) and 14 (35.21).

mysql · try it yourself
-- TODO: only delivered orders, sum the line values, keep the top 3
SELECT d.order_id, d.quantity, d.unit_price, d.discount
FROM order_details AS d
WHERE d.order_id = 4;
+----------+----------+------------+----------+
| order_id | quantity | unit_price | discount |
+----------+----------+------------+----------+
|        4 |        2 |      24.50 |     0.05 |
|        4 |        5 |       2.49 |     0.00 |
+----------+----------+------------+----------+
Show solution
sql
SELECT o.order_id,
       ROUND(SUM(d.quantity * d.unit_price * (1 - d.discount)), 2) AS total
FROM orders AS o
JOIN order_details AS d ON d.order_id = o.order_id
WHERE o.status = 'delivered'
GROUP BY o.order_id
ORDER BY total DESC
LIMIT 3;

7. Sales rep scoreboard

For each Sales Rep, show their first name, the number of orders they handled (orders) and how many of those were cancelled (cancelled). Most orders first, ties by first name.

Expected: Linus 8 (1 cancelled), Maya 8 (0), Omar 6 (1).

mysql · try it yourself
-- TODO: count orders per rep and add the cancelled column
SELECT e.first_name, COUNT(o.order_id) AS orders
FROM employees AS e
LEFT JOIN orders AS o ON o.employee_id = e.employee_id
GROUP BY e.employee_id, e.first_name
ORDER BY e.employee_id;
+------------+--------+
| first_name | orders |
+------------+--------+
| Grace      |      0 |
| Alan       |      0 |
| Ada        |      0 |
| Linus      |      8 |
| Maya       |      8 |
| Omar       |      6 |
| Tom        |      0 |
| Sara       |      0 |
+------------+--------+
Show solution
sql
SELECT e.first_name,
       COUNT(o.order_id) AS orders,
       SUM(CASE WHEN o.status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM employees AS e
LEFT JOIN orders AS o ON o.employee_id = e.employee_id
WHERE e.title = 'Sales Rep'
GROUP BY e.employee_id, e.first_name
ORDER BY orders DESC, e.first_name;

The starter also lists the managers and packers with 0 orders, which is what the LEFT JOIN is for; the WHERE on the title removes them.

8. Slow shipments

List orders that took 3 days or more to ship (from order_date to shipped_date), with a days column, slowest first, then by order id.

Expected: order 7 with 4 days, then orders 10, 12 and 17 with 3 days.

mysql · try it yourself
-- TODO: compute the days and keep the slow ones
SELECT order_id, order_date, shipped_date
FROM orders
WHERE order_id <= 3;
+----------+------------+--------------+
| order_id | order_date | shipped_date |
+----------+------------+--------------+
|        1 | 2025-01-05 | 2025-01-07   |
|        2 | 2025-01-09 | 2025-01-10   |
|        3 | 2025-01-18 | 2025-01-20   |
+----------+------------+--------------+
Show solution
sql
SELECT order_id, order_date, shipped_date,
       DATEDIFF(shipped_date, order_date) AS days
FROM orders
WHERE DATEDIFF(shipped_date, order_date) >= 3
ORDER BY days DESC, order_id;

Unshipped orders drop out automatically: DATEDIFF with a NULL date is NULL, and NULL >= 3 is not true.

9. A price increase

All Dairy products get 5 % more expensive, rounded to cents. Write the UPDATE so that it finds the category by name, then show the dairy products' new prices.

Expected: Whole Milk 1.52, Aged Gruyere 8.35, Greek Yogurt 4.15, Salted Butter 2.99.

mysql · try it yourself
-- TODO: turn this into an UPDATE that uses the category name
SELECT name, unit_price, ROUND(unit_price * 1.05, 2) AS new_price
FROM products
WHERE category_id = 3;
+--------------------+------------+-----------+
| name               | unit_price | new_price |
+--------------------+------------+-----------+
| Whole Milk 1L      |       1.45 |      1.52 |
| Aged Gruyere 250g  |       7.95 |      8.35 |
| Greek Yogurt 500g  |       3.95 |      4.15 |
| Salted Butter 250g |       2.85 |      2.99 |
+--------------------+------------+-----------+
Show solution
sql
UPDATE products
SET unit_price = ROUND(unit_price * 1.05, 2)
WHERE category_id = (SELECT category_id FROM categories WHERE name = 'Dairy');

SELECT name, unit_price FROM products WHERE category_id = 3 ORDER BY product_id;

A join works too: UPDATE products p JOIN categories c ON c.category_id = p.category_id SET p.unit_price = ROUND(p.unit_price * 1.05, 2) WHERE c.name = 'Dairy';

10. Cheapest product per category

For each category, show the category name, its cheapest product and that product's price, cheapest first. Use a window function inside a CTE.

Expected: 6 rows from Produce | Avocado (each) | 1.25 to Beverages | Orange Juice 1L | 3.20.

mysql · try it yourself
-- TODO: rank products inside each category and keep rank 1
SELECT c.name AS category, p.name, p.unit_price
FROM products AS p
JOIN categories AS c ON c.category_id = p.category_id
WHERE c.category_id = 4
ORDER BY p.unit_price;
+----------+----------------------+------------+
| category | name                 | unit_price |
+----------+----------------------+------------+
| Produce  | Avocado (each)       |       1.25 |
| Produce  | Cherry Tomatoes 500g |       2.75 |
| Produce  | Gala Apples 1kg      |       2.99 |
+----------+----------------------+------------+
Show solution
sql
WITH ranked AS (
    SELECT c.name AS category, p.name, p.unit_price,
           RANK() OVER (PARTITION BY c.category_id ORDER BY p.unit_price) AS pos
    FROM products AS p
    JOIN categories AS c ON c.category_id = p.category_id
)
SELECT category, name, unit_price
FROM ranked
WHERE pos = 1
ORDER BY unit_price;

With RANK(), two products sharing the lowest price would both be listed; ROW_NUMBER() would pick just one of them.

Test yourself

In exercise 7, why is the title filter in WHERE rather than in the LEFT JOIN's ON clause?

  1. ON can't contain text comparisons
  2. The filter is on the left table; in ON it wouldn't remove the other employees
  3. WHERE is faster
  4. There is no difference

In exercise 8, what happens to orders whose shipped_date is NULL?

  1. They are listed with 0 days
  2. They cause an error
  3. They are filtered out because DATEDIFF returns NULL
  4. They are listed with NULL days

Which function would list only ONE product per category even if two tie for the lowest price?

  1. RANK()
  2. DENSE_RANK()
  3. ROW_NUMBER()
  4. NTILE(1)