
SQL Exercises for Beginners: 20 Practice Problems With Solutions
Paste one setup script, then work through 20 SQL exercises from SELECT basics to joins and subqueries. Each one has a hint, a solution and the exact result to check against.
The fastest way to practice SQL as a beginner is to write queries against a small database and check your result against a known answer. This page gives you one copy-paste setup script for a tiny bookshop database and 20 exercises, graded from SELECT basics to joins and subqueries. Each exercise has a hint, a solution, the exact expected result and a common mistake. Every query was run in SQLite and PostgreSQL and returns the same rows in both.
| # | Exercise | Skill |
|---|---|---|
| 1 | Pick columns | SELECT |
| 2 | Filter by genre | WHERE |
| 3 | Sort by price | ORDER BY |
| 4 | Three most expensive books | LIMIT |
| 5 | List each genre once | DISTINCT |
| 6 | Orders in March | BETWEEN |
| 7 | Titles that start with "The" | LIKE |
| 8 | Customers without a city | IS NULL |
| 9 | Count rows and values | COUNT |
| 10 | Books sold | SUM |
| 11 | Price range and average | MIN, MAX, AVG |
| 12 | Orders per customer | GROUP BY |
| 13 | Repeat customers | HAVING |
| 14 | Book titles from April onward | INNER JOIN |
| 15 | Every customer’s order count | LEFT JOIN |
| 16 | Books nobody ordered | Rows without a match |
| 17 | Revenue per genre | JOIN with GROUP BY |
| 18 | Sci-fi buyers | Subquery with IN |
| 19 | Price labels | CASE |
| 20 | Top two spenders | WITH and a tie-breaker |
How to run these exercises
You need somewhere to run SQL. Any of these work:
- The sqlite3 command-line tool. Many computers already have it: type
sqlite3 --versionin a terminal to check. If not, download the command-line tools from the SQLite download page. Save the setup script assetup.sql, runsqlite3 shop.db, then type.read setup.sql. Type.mode box(or.headers on) first so you can see column names in your results. - A free online SQL playground that supports SQLite or PostgreSQL, such as DB Fiddle. Paste the setup script into the schema panel and your query into the query panel.
- PostgreSQL on your computer, from the PostgreSQL download page. Create an empty database, then run the setup script in
psqlor a graphical client like pgAdmin.
The setup script also runs in MySQL and SQL Server, but the solutions are written for SQLite and PostgreSQL. In DB Fiddle, pick SQLite or PostgreSQL in the engine menu, since it defaults to MySQL. MySQL needs CAST(... AS SIGNED) in exercise 11, SQL Server uses TOP instead of LIMIT in exercises 4 and 20, and other databases may need small changes.
If you haven’t run a query before, see how to run an SQL query for a step-by-step walkthrough.
If you change rows while experimenting, run the setup script again. It drops the three tables first, so you always start from the same data.
The practice database
The database is a tiny online bookshop with three tables:
| Table | Columns |
|---|---|
| customers | id, name, city |
| books | id, title, genre, price_cents |
| orders | id, customer_id, book_id, quantity, order_date |
Each order is one book bought by one customer. orders.customer_id points to customers.id, and orders.book_id points to books.id. Prices are whole numbers of cents (1299 means 12.99), so every calculation stays exact. Dates use the YYYY-MM-DD format.
The data is small on purpose, with a few traps that real data has too: one customer has no city (a NULL), one customer has never ordered, one book has never been ordered, some customers ordered more than once, and two customers spent exactly the same amount.
Copy the whole script and run it once:
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS books;
DROP TABLE IF EXISTS
customers;
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100)
NOT NULL,
city VARCHAR(100)
);
CREATE TABLE books (
id INTEGER PRIMARY KEY,
title VARCHAR(100)
NOT NULL,
genre VARCHAR(100)
NOT NULL,
price_cents INTEGER
NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER
NOT NULL
REFERENCES
customers (id),
book_id INTEGER NOT NULL
REFERENCES books (id),
quantity INTEGER NOT NULL,
order_date DATE NOT NULL
);
INSERT INTO customers
(id, name, city)
VALUES
(1, 'Ana', 'Lisbon'),
(2, 'Ben', 'Leeds'),
(3, 'Chen', 'Lisbon'),
(4, 'Dara', NULL),
(5, 'Eli', 'Porto'),
(6, 'Fay', 'Leeds'),
(7, 'Gus', 'Porto');
INSERT INTO books
(id, title, genre,
price_cents)
VALUES
(1, 'The Last Map',
'Fiction', 1299),
(2, 'Salt Roads',
'History', 1850),
(3, 'Star Engines',
'Sci-fi', 999),
(4, 'The Quiet Sea',
'Fiction', 1299),
(5, 'Bread Basics',
'Cooking', 2400),
(6, 'Moon Harbor',
'Sci-fi', 1450),
(7, 'Old Empires',
'History', 2100),
(8, 'Soup Season',
'Cooking', 1499);
INSERT INTO orders
(id, customer_id,
book_id, quantity,
order_date)
VALUES
(1, 1, 1, 1, '2026-03-02'),
(2, 1, 5, 1, '2026-03-05'),
(3, 2, 3, 2, '2026-03-09'),
(4, 3, 4, 2, '2026-03-14'),
(5, 4, 6, 1, '2026-03-20'),
(6, 2, 2, 1, '2026-04-02'),
(7, 5, 7, 1, '2026-04-08'),
(8, 1, 3, 1, '2026-04-15'),
(9, 6, 1, 3, '2026-04-21'),
(10, 3, 1, 1, '2026-04-28');
SQL ignores line breaks, so the short lines are only there to fit small screens. To learn more about the statements in the script, see how to create a table in SQL and how to insert data in SQL.
Try each exercise before you read the solution. Your query is correct when it returns the same rows as the expected result. It doesn’t have to match the solution word for word.
Level 1: Basics
1. Pick columns
Show the title and price_cents of every book. Any row order is fine.
Hint: list the columns you want after SELECT, separated by commas.
Solution
SELECT title, price_cents
FROM books;
Expected result:
| title | price_cents |
|---|---|
| The Last Map | 1299 |
| Salt Roads | 1850 |
| Star Engines | 999 |
| The Quiet Sea | 1299 |
| Bread Basics | 2400 |
| Moon Harbor | 1450 |
| Old Empires | 2100 |
| Soup Season | 1499 |
SELECT chooses the columns and FROM chooses the table. Without ORDER BY, the database may return rows in any order, so yours can differ from the table above. More in how to use SELECT in SQL.
Common mistake: leaving out the comma, as in SELECT title price_cents. The database reads price_cents as a new name for title, so you get one column of titles labeled price_cents, with no error.
2. Filter by genre
Show the title and price_cents of all History books. Any row order is fine.
Hint: use WHERE with the text value in single quotes.
Solution
SELECT title, price_cents
FROM books
WHERE genre = 'History';
Expected result:
| title | price_cents |
|---|---|
| Salt Roads | 1850 |
| Old Empires | 2100 |
WHERE keeps only the rows where the condition is true. Text values go in single quotes. See how to use WHERE in SQL for more conditions.
Common mistake: writing "History" in double quotes. Double quotes are for column names, so PostgreSQL fails with an error, and so does the sqlite3 command-line tool from version 3.41 ("no such column"). Some other SQLite tools find no column called History and silently treat it as text, which hides the mistake. Use single quotes so the query works everywhere.
3. Sort by price
Show the title and price_cents of books that cost less than 1500 cents, cheapest first. If two books cost the same, sort them by title.
Hint: ORDER BY can take more than one column.
Solution
SELECT title, price_cents
FROM books
WHERE price_cents < 1500
ORDER BY price_cents, title;
Expected result:
| title | price_cents |
|---|---|
| Star Engines | 999 |
| The Last Map | 1299 |
| The Quiet Sea | 1299 |
| Moon Harbor | 1450 |
| Soup Season | 1499 |
ORDER BY sorts from smallest to largest by default. The second column, title, only decides the order when the first column is tied, like the two books at 1299. Read more in how to use ORDER BY in SQL.
Common mistake: writing WHERE price_cents < 15. Prices are stored in cents, so 15 means 15 cents.
4. Three most expensive books
Show the title and price_cents of the three most expensive books, most expensive first.
Hint: sort with DESC, then keep the first rows with LIMIT.
Solution
SELECT title, price_cents
FROM books
ORDER BY price_cents DESC,
title
LIMIT 3;
Expected result:
| title | price_cents |
|---|---|
| Bread Basics | 2400 |
| Old Empires | 2100 |
| Salt Roads | 1850 |
DESC sorts from largest to smallest, and LIMIT 3 keeps the first three rows of that sorted result. LIMIT works in SQLite, PostgreSQL and MySQL; SQL Server uses TOP instead. See how to use LIMIT in SQL.
Common mistake: using LIMIT without ORDER BY. You get three rows, but not necessarily the three you asked for.
5. List each genre once
Show each genre only once, in alphabetical order.
Hint: add one keyword right after SELECT.
Solution
SELECT DISTINCT genre
FROM books
ORDER BY genre;
Expected result:
| genre |
|---|
| Cooking |
| Fiction |
| History |
| Sci-fi |
There are eight books but only four genres. DISTINCT removes duplicate rows from the result. More in how to use DISTINCT in SQL.
Common mistake: adding another column, like SELECT DISTINCT genre, title. DISTINCT applies to the whole row, so every book comes back again.
6. Orders in March
Show the id and order_date of every order placed in March 2026, sorted by id.
Hint: BETWEEN includes both the first and the last value.
Solution
SELECT id, order_date
FROM orders
WHERE order_date
BETWEEN '2026-03-01'
AND '2026-03-31'
ORDER BY id;
Expected result:
| id | order_date |
|---|---|
| 1 | 2026-03-02 |
| 2 | 2026-03-05 |
| 3 | 2026-03-09 |
| 4 | 2026-03-14 |
| 5 | 2026-03-20 |
Dates in the YYYY-MM-DD format sort the same way as text and as dates, so range checks work in both databases. Read more in how to use BETWEEN in SQL.
Common mistake: writing dates in another format, like '3/1/2026'. SQLite compares it as text and returns no rows. PostgreSQL reads it according to the server’s DateStyle setting: month first, it happens to work, but day first, '3/31/2026' fails with an out-of-range error and '3/1/2026' quietly means 3 January. Stick to YYYY-MM-DD.
7. Titles that start with "The"
Show the title of every book whose title starts with "The", in alphabetical order.
Hint: in a LIKE pattern, % matches any number of characters.
Solution
SELECT title
FROM books
WHERE title LIKE 'The%'
ORDER BY title;
Expected result:
| title |
|---|
| The Last Map |
| The Quiet Sea |
'The%' means "The" followed by anything. A pattern like '%Sea' would match titles that end with "Sea". See how to use LIKE in SQL.
Common mistake: expecting LIKE to ignore case everywhere. LIKE 'the%' finds both books in SQLite but none in PostgreSQL. When case shouldn’t matter, use LOWER(title) LIKE 'the%'.
8. Customers without a city
Show the id and name of customers who have no city recorded.
Hint: a missing value is NULL, and it needs its own operator.
Solution
SELECT id, name
FROM customers
WHERE city IS NULL;
Expected result:
| id | name |
|---|---|
| 4 | Dara |
NULL means "unknown", so it isn’t equal to anything, not even another NULL. Use IS NULL to test for a missing value. Learn more in how to handle NULL in SQL.
Common mistake: writing WHERE city = NULL. It runs without an error but returns no rows.
Level 2: Aggregation
Aggregate functions turn many rows into one value, like a count or a total. GROUP BY gives you one value per group.
9. Count rows and values
Count all customers, and count how many of them have a city. Name the columns customers and with_city.
Hint: COUNT(*) counts rows. COUNT(column) counts values that aren’t NULL.
Solution
SELECT
COUNT(*) AS customers,
COUNT(city) AS with_city
FROM customers;
Expected result:
| customers | with_city |
|---|---|
| 7 | 6 |
There are seven customers, but Dara’s city is NULL, so COUNT(city) skips that row. AS gives each result column a name. See how to use COUNT in SQL.
Common mistake: using COUNT(city) to count customers. It quietly leaves out rows where the city is missing.
10. Books sold
Find the total number of books sold across all orders. Name the column books_sold.
Hint: one order can contain more than one copy.
Solution
SELECT
SUM(quantity)
AS books_sold
FROM orders;
Expected result:
| books_sold |
|---|
| 14 |
SUM adds up the quantity of all ten orders.
Common mistake: using COUNT(*) instead. It returns 10, the number of orders, not the number of books.
11. Price range and average
Show the lowest, highest and average book price in cents. Name the columns min_cents, max_cents and avg_cents, and turn the average into a whole number with CAST(... AS INTEGER). The average of these prices happens to be a whole number, so no rounding is needed.
Hint: MIN, MAX and AVG work like SUM. Put the whole AVG(...) inside the CAST.
Solution
SELECT
MIN(price_cents)
AS min_cents,
MAX(price_cents)
AS max_cents,
CAST(AVG(price_cents)
AS INTEGER) AS avg_cents
FROM books;
Expected result:
| min_cents | max_cents | avg_cents |
|---|---|---|
| 999 | 2400 | 1612 |
AVG returns a decimal number, shown as 1612.0 in SQLite and 1612.0000000000000000 in PostgreSQL. CAST turns it into a whole number so both show 1612. More on MIN and MAX and AVG.
Common mistake: expecting CAST to round the same way everywhere. Here the average is exactly 1612, but for an average like 1612.6, PostgreSQL rounds to 1613 and SQLite cuts it to 1612.
12. Orders per customer
Count the orders of each customer who has ordered. Show customer_id and order_count, sorted by customer_id.
Hint: GROUP BY the column you want one row for.
Solution
SELECT
customer_id,
COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
ORDER BY customer_id;
Expected result:
| customer_id | order_count |
|---|---|
| 1 | 3 |
| 2 | 2 |
| 3 | 2 |
| 4 | 1 |
| 5 | 1 |
| 6 | 1 |
GROUP BY puts the rows with the same customer_id into one group, and COUNT(*) counts the rows in each group. Customer 7 has no orders, so there’s no row for it. Exercise 15 shows how to include it. See how to use GROUP BY in SQL.
Common mistake: adding order_date to this query without putting it in GROUP BY or inside an aggregate. PostgreSQL rejects it, and SQLite returns the date from an arbitrary row in the group.
13. Repeat customers
Show the customer_id and order_count of customers with more than one order, sorted by customer_id.
Hint: you can’t filter on COUNT(*) in WHERE.
Solution
SELECT
customer_id,
COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 1
ORDER BY customer_id;
Expected result:
| customer_id | order_count |
|---|---|
| 1 | 3 |
| 2 | 2 |
| 3 | 2 |
WHERE filters rows before they’re grouped, and HAVING filters groups after the counts exist. Read more in how to use HAVING in SQL.
Common mistake: writing WHERE COUNT(*) > 1. Both databases stop with an error, because aggregates aren’t allowed in WHERE.
Level 3: Joins
Joins combine rows from two or more tables using matching ids, for example orders.book_id = books.id.
14. Book titles from April onward
For every order placed from April 2026 onward, so on or after 2026-04-01, show the order id and the book title, sorted by order id.
Hint: join orders to books on the book id.
Solution
SELECT o.id, b.title
FROM orders AS o
JOIN books AS b
ON b.id = o.book_id
WHERE o.order_date
>= '2026-04-01'
ORDER BY o.id;
Expected result:
| id | title |
|---|---|
| 6 | Salt Roads |
| 7 | Old Empires |
| 8 | Star Engines |
| 9 | The Last Map |
| 10 | The Last Map |
JOIN (short for INNER JOIN) pairs each order with the book whose id matches its book_id. The short names o and b save typing. "The Last Map" appears twice because two orders point to the same book. See how to use INNER JOIN in SQL.
Common mistake: writing WHERE id >= ... or ON id = book_id without the table name. Both tables have an id column, so the database stops with an "ambiguous column" error.
15. Every customer’s order count
Show every customer’s name and how many orders they placed as order_count, including customers with no orders. Sort by name.
Hint: LEFT JOIN keeps every row from the table written first.
Solution
SELECT
c.name,
COUNT(o.id) AS order_count
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY c.name;
Expected result:
| name | order_count |
|---|---|
| Ana | 3 |
| Ben | 2 |
| Chen | 2 |
| Dara | 1 |
| Eli | 1 |
| Fay | 1 |
| Gus | 0 |
Gus has no orders, so LEFT JOIN keeps the Gus row and fills the order columns with NULL. COUNT(o.id) skips that NULL and gives 0. Grouping by c.id as well as c.name keeps two customers with the same name apart. More in how to use LEFT JOIN in SQL.
Common mistake: using COUNT(*) here. It counts the Gus row with its empty order columns, so Gus gets 1 instead of 0.
16. Books nobody ordered
Show the id and title of books that have never been ordered.
Hint: after a LEFT JOIN, a book with no orders has NULL in every order column.
Solution
SELECT b.id, b.title
FROM books AS b
LEFT JOIN orders AS o
ON o.book_id = b.id
WHERE o.id IS NULL;
Expected result:
| id | title |
|---|---|
| 8 | Soup Season |
The LEFT JOIN keeps all eight books. Only Soup Season has no matching order, so it’s the only row where o.id is NULL. You can also solve this with NOT EXISTS, explained in how to use EXISTS in SQL.
Common mistake: using JOIN instead of LEFT JOIN. An inner join drops books without orders before WHERE runs, so you get no rows.
17. Revenue per genre
Show each genre that has sales and its revenue in cents as revenue_cents (quantity times price, added up). Sort by revenue, highest first, then by genre.
Hint: join first, then group. You can multiply inside SUM.
Solution
SELECT
b.genre,
SUM(o.quantity
* b.price_cents)
AS revenue_cents
FROM orders AS o
JOIN books AS b
ON b.id = o.book_id
GROUP BY b.genre
ORDER BY revenue_cents DESC,
b.genre;
Expected result:
| genre | revenue_cents |
|---|---|
| Fiction | 9093 |
| Sci-fi | 4447 |
| History | 3950 |
| Cooking | 2400 |
The join gives each order its book’s genre and price. GROUP BY then makes one group per genre, and SUM adds up quantity times price for each order in it. Fay’s three copies of The Last Map alone make up 3897 of Fiction’s 9093 cents. Read more about joins.
Common mistake: writing SUM(b.price_cents). That ignores quantity, so orders of two or three copies count as one.
Level 4: Stretch exercises
18. Sci-fi buyers
Show the name of every customer who bought at least one Sci-fi book, in alphabetical order.
Hint: first find the customer ids in a subquery, then use IN.
Solution
SELECT name
FROM customers
WHERE id IN (
SELECT o.customer_id
FROM orders AS o
JOIN books AS b
ON b.id = o.book_id
WHERE b.genre = 'Sci-fi'
)
ORDER BY name;
Expected result:
| name |
|---|
| Ana |
| Ben |
| Dara |
The subquery in brackets returns the ids of customers who ordered a Sci-fi book: 1, 2 and 4. The outer query keeps customers whose id is in that list, using the SQL IN operator, and each customer appears once. See how to write subqueries in SQL.
Common mistake: writing id = (SELECT ...). PostgreSQL fails because the subquery returns more than one row, and SQLite silently uses only the first one.
19. Price labels
Show each book’s title and a label: "budget" under 1500 cents, "standard" from 1500 to 1999, and "premium" from 2000. Sort by book id.
Hint: CASE checks its WHEN conditions from top to bottom.
Solution
SELECT
title,
CASE
WHEN price_cents < 1500
THEN 'budget'
WHEN price_cents < 2000
THEN 'standard'
ELSE 'premium'
END AS label
FROM books
ORDER BY id;
Expected result:
| title | label |
|---|---|
| The Last Map | budget |
| Salt Roads | standard |
| Star Engines | budget |
| The Quiet Sea | budget |
| Bread Basics | premium |
| Moon Harbor | budget |
| Old Empires | premium |
| Soup Season | budget |
CASE returns the value of the first WHEN that is true. A price under 1500 never reaches the second check, so price_cents < 2000 only needs the upper limit. Read more in how to use CASE in SQL.
Common mistake: forgetting ELSE. Rows that match no WHEN get NULL instead of a label.
20. Top two spenders
Use WITH to work out how much each customer spent in cents, then show the name and total of the two biggest spenders. Return exactly two rows, highest total first, and break ties by name.
Hint: WITH names a query so you can use it like a table.
Solution
WITH spend AS (
SELECT
o.customer_id,
SUM(o.quantity
* b.price_cents)
AS total
FROM orders AS o
JOIN books AS b
ON b.id = o.book_id
GROUP BY o.customer_id
)
SELECT c.name, s.total
FROM spend AS s
JOIN customers AS c
ON c.id = s.customer_id
ORDER BY s.total DESC,
c.name
LIMIT 2;
Expected result:
| name | total |
|---|---|
| Ana | 4698 |
| Chen | 3897 |
The WITH part, called a common table expression (CTE), builds a small result named spend with one total per customer. The main query joins it to customers for the names. Chen and Fay both spent 3897, so sorting by name decides that Chen takes the second place.
Common mistake: sorting only by total. With a tie at the cut-off, the database can return either Chen or Fay.
What to practice next
- Solve each exercise a second way. For example, rewrite exercise 16 with
NOT EXISTSor exercise 18 with a join andDISTINCT. On this data the join alone happens to give the same rows, but you needDISTINCTwhen a customer has several Sci-fi orders. - Add your own rows to the setup script, predict the new result, then run the query to check.
- Write new questions for the same data, like "which city spent the most?", and answer them.
- Keep the SQL cheat sheet open while you work.
- When these feel easy, move on to a bigger public dataset, where you can’t check every row by eye.
Learn SQL with Mimo
If you want guided practice, Mimo’s SQL course teaches SQL with interactive lessons and exercises that give instant feedback. It covers the basics, filters, aggregate functions, joins and subqueries. You learn at your own pace and get a certificate of completion when you finish.
Sign up and start with your first lesson.

