SQL Exercises With Solutions: Beginner
19 beginner SQL exercises on one practice shop database, each with the expected result, a hint and an explained solution: selecting and filtering, sorting, NULLs, pattern matching, computed columns, CASE, grouping and first joins.
kvi5hnuCode Sprout team member10 min readOn this page
This is the first of four graded exercise sets. Each one uses the same small shop database, so you get to know the data and can concentrate on the SQL. The sets get harder as they go:
| Set | Covers | Articles |
|---|---|---|
| Beginner (this one) | SELECT, WHERE, ORDER BY, NULLs, expressions, CASE, GROUP BY, simple joins | 1–19 |
| Intermediate | multi-table joins, outer joins, HAVING, subqueries, CTEs, set operations | 12–25 |
| Advanced | window functions, running totals, ranking, gaps, recursive queries | 26–30, 44–48 |
| Challenge set | interview-style problems combining everything | all |
How to use these exercises
For each exercise, write your query first, then compare your result with the expected result. Open the hint only if you're stuck, and the answer once you have a result, or after a real attempt. In the expected results, NULL is shown as (null), as psql displays it after \pset null '(null)'. Your query doesn't have to match the answer word for word. Any query giving the same rows, in the same order when the task asks for one, is correct.
The runnable block below creates the whole database and shows how many rows each table has. Edit the last query in it to try your answers, or load the same statements into any PostgreSQL database.
The practice database
| Table | Rows | What it holds |
|---|---|---|
categories | 7 | product categories in a three-level tree: Outdoor at the top, the departments Camping and Hiking below it, and the four categories that hold products; parent_id points to the parent category |
products | 12 | name, category_id, price, stock, and discontinued |
customers | 10 | name, city (may be NULL), country code, joined_on, and referred_by another customer |
employees | 6 | sales staff, with manager_id pointing to their manager |
orders | 22 | customer_id, the employee_id who handled it, placed_on, shipped_on (NULL until shipped), and status |
order_items | 35 | one row per product in an order: qty, unit_price at the time of sale, and discount as a fraction (0.10 = 10%) |
payments | 21 | payments against orders, paid_on, amount and method; some orders were paid in two instalments |
An order line's value is qty * unit_price * (1 - discount). Prices can change, which is why order_items keeps its own unit_price.
-- Practice shop database for the SQL exercises
CREATE TABLE categories (
category_id INTEGER PRIMARY KEY,
name VARCHAR(30) NOT NULL,
parent_id INTEGER REFERENCES categories (category_id)
);
INSERT INTO categories VALUES
(1, 'Outdoor', NULL), (2, 'Camping', 1), (3, 'Hiking', 1),
(4, 'Tents', 2), (5, 'Lighting', 2), (6, 'Packs', 3), (7, 'Clothing', 3);
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category_id INTEGER NOT NULL REFERENCES categories (category_id),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
discontinued BOOLEAN NOT NULL DEFAULT false
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 4, 249.99, 12, false),
(2, 'Summit 4 tent', 4, 489.00, 3, false),
(3, 'Breeze 1 tent', 4, 159.00, 0, true),
(4, 'Glow head torch', 5, 34.50, 40, false),
(5, 'Basecamp lantern', 5, 27.00, 15, false),
(6, 'Spark mini light', 5, 12.00, 60, false),
(7, 'Trail 30 backpack', 6, 89.95, 22, false),
(8, 'Day 18 backpack', 6, 54.00, 0, false),
(9, 'Summit 60 pack', 6, 199.00, 5, false),
(10, 'Merino socks', 7, 16.00, 75, false),
(11, 'Rain shell jacket', 7, 129.00, 9, false),
(12, 'Fleece midlayer', 7, 69.00, 0, true);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
country CHAR(2) NOT NULL,
joined_on DATE NOT NULL,
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', 'IN', DATE '2025-06-14', NULL),
(2, 'Ben Okafor', 'Leeds', 'GB', DATE '2025-08-02', 1),
(3, 'Chen Wei', 'Pune', 'IN', DATE '2025-09-20', 1),
(4, 'Dana Cruz', 'York', 'GB', DATE '2025-11-05', 2),
(5, 'Eli Novak', 'Leeds', 'GB', DATE '2025-12-11', NULL),
(6, 'Farah Haddad', NULL, 'IN', DATE '2026-01-03', 3),
(7, 'Gita Bose', 'Mumbai', 'IN', DATE '2026-01-19', NULL),
(8, 'Hugo Lefevre', 'Lyon', 'FR', DATE '2026-02-07', 5),
(9, 'Isha Menon', 'Mumbai', 'IN', DATE '2026-02-22', 7),
(10, 'Jonas Berg', 'Oslo', 'NO', DATE '2026-03-30', NULL);
CREATE TABLE employees (
employee_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
title VARCHAR(30) NOT NULL,
manager_id INTEGER REFERENCES employees (employee_id),
hired_on DATE NOT NULL
);
INSERT INTO employees VALUES
(1, 'Maya Iyer', 'Head of Sales', NULL, DATE '2022-04-01'),
(2, 'Noah Price', 'Sales Lead', 1, DATE '2023-01-16'),
(3, 'Omar Said', 'Sales Associate', 2, DATE '2024-05-06'),
(4, 'Priya Nair', 'Sales Associate', 2, DATE '2024-09-23'),
(5, 'Quinn Adams', 'Sales Lead', 1, DATE '2023-07-03'),
(6, 'Rosa Lima', 'Sales Associate', 5, DATE '2025-10-13');
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
employee_id INTEGER REFERENCES employees (employee_id),
placed_on DATE NOT NULL,
shipped_on DATE,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(1001, 1, 3, DATE '2026-01-07', DATE '2026-01-09', 'shipped'),
(1002, 2, 4, DATE '2026-01-13', DATE '2026-01-18', 'delivered'),
(1003, 3, 6, DATE '2026-01-20', DATE '2026-01-21', 'shipped'),
(1004, 4, 3, DATE '2026-01-23', DATE '2026-01-28', 'shipped'),
(1005, 5, 4, DATE '2026-01-29', DATE '2026-02-03', 'shipped'),
(1006, 6, 6, DATE '2026-02-03', NULL, 'cancelled'),
(1007, 7, 2, DATE '2026-02-09', DATE '2026-02-14', 'shipped'),
(1008, 8, 5, DATE '2026-02-16', DATE '2026-02-19', 'shipped'),
(1009, 9, 3, DATE '2026-02-22', DATE '2026-02-25', 'shipped'),
(1010, 1, 4, DATE '2026-02-25', DATE '2026-02-26', 'delivered'),
(1011, 2, 6, DATE '2026-03-03', DATE '2026-03-04', 'shipped'),
(1012, 3, 3, DATE '2026-03-05', DATE '2026-03-07', 'shipped'),
(1013, 1, 4, DATE '2026-03-07', DATE '2026-03-10', 'shipped'),
(1014, 5, 6, DATE '2026-03-09', DATE '2026-03-18', 'delivered'),
(1015, 7, 3, DATE '2026-03-14', NULL, 'cancelled'),
(1016, 9, 4, DATE '2026-03-21', DATE '2026-03-23', 'shipped'),
(1017, 8, 6, DATE '2026-03-24', DATE '2026-03-27', 'shipped'),
(1018, 2, 5, DATE '2026-03-28', DATE '2026-03-30', 'delivered'),
(1019, 1, 3, DATE '2026-04-01', DATE '2026-04-04', 'shipped'),
(1020, 3, 4, DATE '2026-04-08', DATE '2026-04-13', 'shipped'),
(1021, 4, 3, DATE '2026-04-15', NULL, 'pending'),
(1022, 6, 6, DATE '2026-04-17', NULL, 'pending');
CREATE TABLE order_items (
order_id INTEGER NOT NULL REFERENCES orders (order_id),
product_id INTEGER NOT NULL REFERENCES products (product_id),
qty INTEGER NOT NULL CHECK (qty > 0),
unit_price DECIMAL(8, 2) NOT NULL,
discount DECIMAL(3, 2) NOT NULL DEFAULT 0,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(1001, 4, 2, 32.00, 0.00),
(1001, 8, 1, 54.00, 0.00),
(1002, 9, 1, 199.00, 0.00),
(1003, 10, 2, 15.00, 0.00),
(1003, 7, 2, 89.95, 0.10),
(1004, 3, 1, 159.00, 0.00),
(1004, 11, 1, 129.00, 0.10),
(1004, 2, 1, 489.00, 0.10),
(1005, 10, 2, 15.00, 0.00),
(1005, 12, 2, 69.00, 0.10),
(1006, 1, 1, 249.99, 0.00),
(1006, 9, 1, 199.00, 0.00),
(1007, 4, 3, 34.50, 0.10),
(1008, 3, 1, 159.00, 0.00),
(1008, 4, 1, 34.50, 0.00),
(1009, 3, 1, 159.00, 0.10),
(1009, 10, 1, 16.00, 0.10),
(1010, 9, 1, 199.00, 0.05),
(1010, 8, 2, 54.00, 0.05),
(1011, 10, 1, 16.00, 0.00),
(1011, 6, 1, 12.00, 0.00),
(1012, 5, 3, 27.00, 0.10),
(1013, 3, 1, 159.00, 0.00),
(1013, 6, 1, 12.00, 0.05),
(1014, 12, 2, 69.00, 0.00),
(1014, 8, 2, 54.00, 0.05),
(1015, 9, 1, 199.00, 0.00),
(1016, 4, 3, 34.50, 0.05),
(1016, 7, 2, 89.95, 0.00),
(1017, 6, 3, 12.00, 0.00),
(1018, 8, 2, 54.00, 0.00),
(1019, 6, 3, 12.00, 0.00),
(1020, 12, 1, 69.00, 0.00),
(1021, 12, 2, 69.00, 0.10),
(1022, 6, 1, 12.00, 0.00);
CREATE TABLE payments (
payment_id INTEGER PRIMARY KEY,
order_id INTEGER NOT NULL REFERENCES orders (order_id),
paid_on DATE NOT NULL,
amount DECIMAL(8, 2) NOT NULL,
method VARCHAR(10) NOT NULL
);
INSERT INTO payments VALUES
(1, 1001, DATE '2026-01-07', 118.00, 'paypal'),
(2, 1002, DATE '2026-01-13', 199.00, 'card'),
(3, 1003, DATE '2026-01-20', 95.96, 'paypal'),
(4, 1003, DATE '2026-02-03', 95.95, 'paypal'),
(5, 1004, DATE '2026-01-23', 715.20, 'card'),
(6, 1005, DATE '2026-01-29', 154.20, 'card'),
(7, 1007, DATE '2026-02-09', 93.15, 'card'),
(8, 1008, DATE '2026-02-16', 193.50, 'card'),
(9, 1009, DATE '2026-02-22', 78.75, 'card'),
(10, 1009, DATE '2026-03-08', 78.75, 'card'),
(11, 1010, DATE '2026-02-25', 291.65, 'paypal'),
(12, 1011, DATE '2026-03-03', 28.00, 'paypal'),
(13, 1013, DATE '2026-03-07', 170.40, 'upi'),
(14, 1014, DATE '2026-03-09', 240.60, 'card'),
(15, 1016, DATE '2026-03-21', 278.23, 'paypal'),
(16, 1017, DATE '2026-03-24', 18.00, 'card'),
(17, 1017, DATE '2026-04-07', 18.00, 'card'),
(18, 1018, DATE '2026-03-28', 108.00, 'upi'),
(19, 1019, DATE '2026-04-01', 36.00, 'paypal'),
(20, 1020, DATE '2026-04-08', 69.00, 'card'),
(21, 1021, DATE '2026-04-15', 124.20, 'paypal');
SELECT 'categories' AS table_name, COUNT(*) AS row_count FROM categories
UNION ALL SELECT 'products', COUNT(*) FROM products
UNION ALL SELECT 'customers', COUNT(*) FROM customers
UNION ALL SELECT 'employees', COUNT(*) FROM employees
UNION ALL SELECT 'orders', COUNT(*) FROM orders
UNION ALL SELECT 'order_items', COUNT(*) FROM order_items
UNION ALL SELECT 'payments', COUNT(*) FROM payments;
table_name | row_count
-------------+-----------
categories | 7
products | 12
customers | 10
employees | 6
orders | 22
order_items | 35
payments | 21
(7 rows)
Selecting, filtering and sorting
1. Products by price
List every product's name and price, most expensive first.
Expected result:
name | price
-------------------+--------
Summit 4 tent | 489.00
Ridge 2 tent | 249.99
Summit 60 pack | 199.00
Breeze 1 tent | 159.00
Rain shell jacket | 129.00
Trail 30 backpack | 89.95
Fleece midlayer | 69.00
Day 18 backpack | 54.00
Glow head torch | 34.50
Basecamp lantern | 27.00
Merino socks | 16.00
Spark mini light | 12.00
(12 rows)
Answer
SELECT name, price
FROM products
ORDER BY price DESC;
ORDER BY price DESC sorts from highest to lowest. Without an ORDER BY, the database may return rows in any order, so always add one when the order matters (article 9).
2. Out of stock but still sold
Find products with no stock that haven't been discontinued. Show the name and stock.
Expected result:
name | stock
-----------------+-------
Day 18 backpack | 0
(1 row)
Hint
Two conditions joined with AND. discontinued is a boolean column.
Answer
SELECT name, stock
FROM products
WHERE stock = 0
AND NOT discontinued;
A boolean column can be used directly as a condition: NOT discontinued means discontinued = false. Breeze 1 tent and Fleece midlayer also have no stock, but they're discontinued, so they don't need restocking.
3. Indian customers in joining order
List the name, city and joining date of customers in India (country = 'IN'), earliest joiner first.
Expected result:
name | city | joined_on
--------------+--------+------------
Asha Rao | Pune | 2025-06-14
Chen Wei | Pune | 2025-09-20
Farah Haddad | (null) | 2026-01-03
Gita Bose | Mumbai | 2026-01-19
Isha Menon | Mumbai | 2026-02-22
(5 rows)
Answer
SELECT name, city, joined_on
FROM customers
WHERE country = 'IN'
ORDER BY joined_on;
Text values go in single quotes. country is CHAR(2), so compare it with the two-letter code. Farah Haddad's city shows as (null), meaning unknown.
4. Customers with no city
Find customers whose city is unknown.
Expected result:
customer_id | name
-------------+--------------
6 | Farah Haddad
(1 row)
Hint
city = NULL never matches anything.
Answer
SELECT customer_id, name
FROM customers
WHERE city IS NULL;
Any comparison with NULL, including = NULL, is unknown rather than true, so it never selects a row. Test for missing values with IS NULL (article 8).
5. Mid-priced products
List products priced from 30 to 100, inclusive, cheapest first.
Expected result:
name | price
-------------------+-------
Glow head torch | 34.50
Day 18 backpack | 54.00
Fleece midlayer | 69.00
Trail 30 backpack | 89.95
(4 rows)
Answer
SELECT name, price
FROM products
WHERE price BETWEEN 30 AND 100
ORDER BY price;
BETWEEN 30 AND 100 includes both ends, so it's the same as price >= 30 AND price <= 100. With numbers that's fine; with timestamps, prefer a half-open range (article 68).
6. Every kind of tent
Find products with "tent" anywhere in the name, in any letter case.
Expected result:
name
---------------
Breeze 1 tent
Ridge 2 tent
Summit 4 tent
(3 rows)
Answer
SELECT name
FROM products
WHERE name ILIKE '%tent%'
ORDER BY name;
% matches any run of characters, including none. ILIKE is PostgreSQL's case-insensitive LIKE. Portable alternatives are LOWER(name) LIKE '%tent%' or a case-insensitive collation (article 7).
7. Countries we sell to
List each country that has at least one customer, once, in alphabetical order.
Expected result:
country
---------
FR
GB
IN
NO
(4 rows)
Answer
SELECT DISTINCT country
FROM customers
ORDER BY country;
DISTINCT removes duplicate rows from the result. GROUP BY country gives the same answer here (article 10).
8. The three most expensive products
Show the names and prices of the three most expensive products.
Expected result:
name | price
----------------+--------
Summit 4 tent | 489.00
Ridge 2 tent | 249.99
Summit 60 pack | 199.00
(3 rows)
Answer
SELECT name, price
FROM products
ORDER BY price DESC
FETCH FIRST 3 ROWS ONLY;
FETCH FIRST 3 ROWS ONLY is the standard syntax. LIMIT 3 does the same in PostgreSQL, MySQL and SQLite. If two products tied for third place, you'd get one of them arbitrarily. FETCH FIRST 3 ROWS WITH TIES would return both (article 10).
Expressions and CASE
9. Line values for one order
For order 1004, show each product_id, the quantity, the unit price, the discount, and the line value after discount, rounded to 2 decimal places.
Expected result:
product_id | qty | unit_price | discount | line_value
------------+-----+------------+----------+------------
2 | 1 | 489.00 | 0.10 | 440.10
3 | 1 | 159.00 | 0.00 | 159.00
11 | 1 | 129.00 | 0.10 | 116.10
(3 rows)
Answer
SELECT product_id, qty, unit_price, discount,
ROUND(qty * unit_price * (1 - discount), 2) AS line_value
FROM order_items
WHERE order_id = 1004
ORDER BY product_id;
Calculations can use any columns of the row. AS line_value names the computed column. Exact DECIMAL arithmetic means there's no floating-point error, and ROUND gives the 2 decimal places a price needs (article 38).
10. Products per price band
Put products into price bands: under 50 is budget, under 150 is mid-range, and anything else is premium. Count the products in each band.
Expected result:
band | products
-----------+----------
budget | 4
mid-range | 4
premium | 4
(3 rows)
Hint
A CASE expression can be used in GROUP BY as well as in SELECT.
Answer
SELECT CASE
WHEN price < 50 THEN 'budget'
WHEN price < 150 THEN 'mid-range'
ELSE 'premium'
END AS band,
COUNT(*) AS products
FROM products
GROUP BY band
ORDER BY MIN(price);
CASE tries its WHEN branches in order and uses the first that's true, so the second branch only sees prices of 50 or more. PostgreSQL and MySQL let you group by the alias band. In other databases, repeat the whole CASE in GROUP BY. Ordering by MIN(price) puts the bands in price order instead of alphabetical order.
11. Slow shipments
For orders that have shipped, show the order ID and how many days passed between placing and shipping it. Include only orders that took more than 3 days, slowest first, and by order ID when tied.
Expected result:
order_id | days_to_ship
----------+--------------
1014 | 9
1002 | 5
1004 | 5
1005 | 5
1007 | 5
1020 | 5
(6 rows)
Answer
SELECT order_id, shipped_on - placed_on AS days_to_ship
FROM orders
WHERE shipped_on - placed_on > 3
ORDER BY days_to_ship DESC, order_id;
In PostgreSQL, subtracting one DATE from another gives a whole number of days. Orders that haven't shipped have a NULL shipped_on, so the difference is NULL and the condition excludes them without any extra test. You can't use the alias days_to_ship in WHERE, because WHERE is evaluated before SELECT, but ORDER BY can use it (article 4). Other databases use functions such as DATEDIFF (article 40).
12. Orders in March
List the ID and date of every order placed in March 2026.
Expected result:
order_id | placed_on
----------+------------
1011 | 2026-03-03
1012 | 2026-03-05
1013 | 2026-03-07
1014 | 2026-03-09
1015 | 2026-03-14
1016 | 2026-03-21
1017 | 2026-03-24
1018 | 2026-03-28
(8 rows)
Answer
SELECT order_id, placed_on
FROM orders
WHERE placed_on >= DATE '2026-03-01'
AND placed_on < DATE '2026-04-01'
ORDER BY placed_on;
A half-open range, from the first day of the month up to but excluding the first day of the next, works for dates and timestamps alike, and can use an index on placed_on. EXTRACT(MONTH FROM placed_on) = 3 gives the same rows here, but matches March of every year and can't use a plain index (article 55).
Counting and grouping
13. Orders by status
Count the orders in each status, largest group first.
Expected result:
status | orders
-----------+--------
shipped | 14
delivered | 4
cancelled | 2
pending | 2
(4 rows)
Answer
SELECT status, COUNT(*) AS orders
FROM orders
GROUP BY status
ORDER BY orders DESC, status;
GROUP BY status makes one group per distinct status, and COUNT(*) counts the rows in each (article 19).
14. Takings by payment method
Show the number of payments and the total amount received for each payment method, highest total first.
Expected result:
method | payments | total
--------+----------+---------
card | 11 | 1858.15
paypal | 8 | 1067.99
upi | 2 | 278.40
(3 rows)
Answer
SELECT method, COUNT(*) AS payments, SUM(amount) AS total
FROM payments
GROUP BY method
ORDER BY total DESC;
Several aggregates can be calculated for the same groups. Every column in SELECT is either grouped or inside an aggregate (article 19).
15. Busy customers
Find customers who have placed more than two orders. Show the customer_id and the number of orders.
Expected result:
customer_id | orders
-------------+--------
1 | 4
2 | 3
3 | 3
(3 rows)
Hint
Filtering on a count happens after grouping.
Answer
SELECT customer_id, COUNT(*) AS orders
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 2
ORDER BY orders DESC, customer_id;
WHERE filters rows before they're grouped, so it can't refer to COUNT(*). HAVING filters the groups afterwards (article 19).
First joins
16. April orders with customer names
List the orders placed in April 2026 with the order ID, date, status and the customer's name.
Expected result:
order_id | placed_on | status | customer
----------+------------+---------+--------------
1019 | 2026-04-01 | shipped | Asha Rao
1020 | 2026-04-08 | shipped | Chen Wei
1021 | 2026-04-15 | pending | Dana Cruz
1022 | 2026-04-17 | pending | Farah Haddad
(4 rows)
Answer
SELECT o.order_id, o.placed_on, o.status, c.name AS customer
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.placed_on >= DATE '2026-04-01'
AND o.placed_on < DATE '2026-05-01'
ORDER BY o.placed_on;
The join matches each order with the customer whose key it holds. Table aliases (o, c) keep the query short and make clear which table each column comes from (article 12).
17. Products in the Packs category
List the products in the category named Packs, with their prices, cheapest first. Use the category's name, not its ID.
Expected result:
name | price
-------------------+--------
Day 18 backpack | 54.00
Trail 30 backpack | 89.95
Summit 60 pack | 199.00
(3 rows)
Answer
SELECT p.name, p.price
FROM products p
JOIN categories c ON c.category_id = p.category_id
WHERE c.name = 'Packs'
ORDER BY p.price;
Joining to categories lets you filter by name. Hard-coding category_id = 6 would also work today, but breaks silently if the IDs change.
18. Staff and their managers
List every employee's name and title with their manager's name. The head of sales has no manager, but should still appear.
Expected result:
name | title | manager
-------------+-----------------+-------------
Maya Iyer | Head of Sales | (null)
Noah Price | Sales Lead | Maya Iyer
Omar Said | Sales Associate | Noah Price
Priya Nair | Sales Associate | Noah Price
Quinn Adams | Sales Lead | Maya Iyer
Rosa Lima | Sales Associate | Quinn Adams
(6 rows)
Hint
Join employees to itself, and keep employees without a match.
Answer
SELECT e.name, e.title, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.employee_id = e.manager_id
ORDER BY e.employee_id;
A self-join uses the same table twice under different aliases: e for the employee and m for the manager. An inner join would drop Maya Iyer, whose manager_id is NULL. LEFT JOIN keeps that row, with NULL as the manager (articles 13 and 14).
19. Customers who never ordered
Find customers who have never placed an order.
Expected result:
customer_id | name
-------------+------------
10 | Jonas Berg
(1 row)
Answer
SELECT c.customer_id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;
A LEFT JOIN keeps customers with no orders and fills the order columns with NULLs, and WHERE o.order_id IS NULL keeps just those rows. NOT EXISTS is the other standard way to write this anti-join (article 16).
Common questions
My query gives the same rows in a different order. Is it wrong?
Only if the exercise asks for an order. Without ORDER BY, any order is correct, and the database may change it from one run to the next.
My answer differs from the solution but gives the same result. Which is better? Both are correct. Prefer the one that's easier to read and that would still be right if the data changed, for example a join on a name over a hard-coded ID.
Do these solutions work in MySQL, SQL Server or Oracle?
Mostly. The differences here are ILIKE (PostgreSQL only), date subtraction, grouping by an alias, FETCH FIRST (use LIMIT in MySQL, and OFFSET 0 ROWS FETCH NEXT n ROWS ONLY in SQL Server), DATE '...' literals (SQL Server uses '2026-03-01' or CAST), and the boolean discontinued column (SQL Server uses BIT, compared with = 0).
Summary
WHEREfilters rows,ORDER BYsorts them, andFETCH FIRSTorLIMITkeeps the first few.- Test for missing values with
IS NULL. Comparisons with NULL are never true. - Computed columns,
CASEand date arithmetic all work row by row. GROUP BYwith aggregates summarises groups, andHAVINGfilters them.- Joins combine tables through their keys.
LEFT JOINkeeps rows without a match.
Practice questions
Write a query showing every category's name and how many products it has, including categories with none.
Answer
SELECT c.name, COUNT(p.product_id) AS products
FROM categories c
LEFT JOIN products p ON p.category_id = c.category_id
GROUP BY c.category_id, c.name
ORDER BY c.category_id;
Outdoor, Camping and Hiking hold no products directly, so they show 0. COUNT(p.product_id) counts only matched products, while COUNT(*) would count the NULL-filled row and wrongly show 1.
Why does SELECT customer_id, name, COUNT(*) FROM orders GROUP BY customer_id fail?
Answer
name isn't a column of orders, and even if it were, every selected column must either be grouped or aggregated. Join to customers and group by both customer_id and name.
Previous: SQL Anti-Patterns and How to Fix Them

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.