Sample Schema and Relationships
Run the following script in a disposable PostgreSQL database or schema. The tables are created in dependency order. Primary keys identify rows, and foreign keys enforce the relationships used throughout the exercises.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
customer_name TEXT NOT NULL,
email TEXT
);
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
product_name TEXT NOT NULL
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers(customer_id),
order_date DATE NOT NULL
);
CREATE TABLE order_items (
order_item_id INTEGER PRIMARY KEY,
order_id INTEGER NOT NULL REFERENCES orders(order_id),
product_id INTEGER NOT NULL REFERENCES products(product_id),
quantity INTEGER NOT NULL CHECK (quantity > 0),
unit_price NUMERIC(10, 2) NOT NULL CHECK (unit_price >= 0)
);
INSERT INTO customers (customer_id, customer_name, email) VALUES
(1, 'Alice', 'alice@example.com'),
(2, 'Bob', 'bob@example.com'),
(3, 'Cara', 'cara@example.com'),
(4, 'Dan', 'dan@example.com'),
(5, 'Eva', NULL);
INSERT INTO products (product_id, product_name) VALUES
(1, 'Keyboard'),
(2, 'Mouse'),
(3, 'Monitor stand');
INSERT INTO orders (order_id, customer_id, order_date) VALUES
(101, 1, '2025-01-01'),
(102, 1, '2025-01-02'),
(103, 2, '2025-01-01'),
(104, 3, '2025-01-02'),
(105, 3, '2025-01-03');
INSERT INTO order_items
(order_item_id, order_id, product_id, quantity, unit_price)
VALUES
(1, 101, 1, 2, 20.00),
(2, 101, 2, 1, 10.00),
(3, 102, 3, 1, 30.00),
(4, 103, 1, 4, 20.00),
(5, 104, 1, 2, 20.00),
(6, 104, 2, 1, 10.00),
(7, 105, 3, 1, 30.00);
SQL Dialect and Setup
Execute the script with a PostgreSQL client such as psql or a database IDE. Use a fresh schema or database: running the same CREATE TABLE statements again against existing tables will fail. Avoid running setup scripts in an environment containing valuable data.
All solutions below use PostgreSQL consistently. Other database systems may support similar SQL but require syntax changes, particularly for limiting rows, type declarations, or window-function behavior. Expected results assume the original dataset and the explicit ordering shown in each query. Copy each complete SQL paragraph into your client; HTML displays may collapse its line breaks, but SQL statements remain executable.
Beginner SQL Practice Exercises with Solutions
Begin with the basic question every query must answer: which rows and columns do you need? These exercises introduce filtering, sorting, missing values, and grouping. Compare both the returned values and the number of rows with the expected output.
Exercise 1: Select and Filter Rows
Task: Return the ID and name of each customer whose ID is greater than 2. Sort the result by customer ID.
Solution:
SELECT customer_id, customer_name
FROM customers
WHERE customer_id > 2
ORDER BY customer_id;
Expected result: (3, Cara), (4, Dan), and (5, Eva).
SELECT chooses the columns, while WHERE filters individual rows before they are returned. The explicit ORDER BY makes the displayed sequence predictable. Without it, a database is not required to return rows in primary-key order, even if it often appears to do so during a small test.
Exercise 2: Sort and Limit Results
Task: Return the three most recent orders by date. If orders share a date, put the higher order ID first.
Solution:
SELECT order_id, customer_id, order_date
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 3;
Expected result: (105, 3, 2025-01-03), (104, 3, 2025-01-02), and (102, 1, 2025-01-02).
The second sort key resolves the tie between orders 102 and 104. This matters when a query returns only part of a result set: without a tie-breaker, the last included row may vary. LIMIT 3 is PostgreSQL syntax for restricting the number of returned rows.
Exercise 3: Handle Missing Values with IS NULL
Task: Find customers whose email address is missing.
Solution:
SELECT customer_id, customer_name
FROM customers
WHERE email IS NULL
ORDER BY customer_id;
Expected result: (5, Eva).
Use IS NULL, not email = NULL. SQL treats a comparison with null as unknown rather than true, and a WHERE clause keeps only rows for which its condition is true. To find present values instead, use IS NOT NULL. A null is also different from an empty string, which requires a separate check if your application stores one.
Exercise 4: Count and Group Records
Task: Count orders for each customer who has at least one order. Return customer IDs in ascending order.
Solution:
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
ORDER BY customer_id;
Expected result: (1, 2), (2, 1), and (3, 2).
GROUP BY creates one group for each customer ID present in orders, and COUNT(*) counts the rows in each group. Dan and Eva do not appear because this query starts from the orders table. Including customers with zero orders requires a different starting point and an outer join.
Intermediate SQL Join and Aggregation Exercises with Solutions
Intermediate SQL is often about combining tables without changing the meaning of the data. Before writing a join, identify the intended result grain: one row per customer, one row per order, or one row per order item. This decision determines which joins and aggregates are appropriate.
In this dataset, one customer can have many orders, and one order can have many items. Consequently, joining through both relationships can produce several rows for a single customer or order. Those rows are not necessarily duplicates; they may represent distinct items at a finer grain.
Exercise 5: Join Orders to Customers
Task: List every order with its customer name and date, sorted by order ID.
Solution:
SELECT o.order_id, c.customer_name, o.order_date
FROM orders AS o
INNER JOIN customers AS c
ON c.customer_id = o.customer_id
ORDER BY o.order_id;
Expected result: (101, Alice, 2025-01-01), (102, Alice, 2025-01-02), (103, Bob, 2025-01-01), (104, Cara, 2025-01-02), and (105, Cara, 2025-01-03).
The inner join returns matching rows from both tables. Because every order references exactly one customer, this join produces one row per order. Alice and Cara appear twice because each has two orders; repeated customer names do not imply an incorrect join.
Exercise 6: Find Customers Without Orders Using LEFT JOIN
Task: Find customers who have never placed an order in this dataset.
Solution:
SELECT c.customer_id, c.customer_name
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL
ORDER BY c.customer_id;
Expected result: (4, Dan) and (5, Eva).
The left join preserves every customer. When no order matches, the order columns are null; checking the non-nullable order primary key identifies those unmatched rows. Eva's missing email is unrelated to the test: she qualifies because she has no order.
Exercise 7: Filter Aggregated Results with HAVING
Task: Return customer IDs with more than one order and show their order counts.
Solution:
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 1
ORDER BY customer_id;
Expected result: (1, 2) and (3, 2).
WHERE filters source rows before grouping; HAVING filters groups after aggregation. A date condition in WHERE would change which orders are counted, while the HAVING condition determines which resulting counts are displayed. Make that distinction explicit when translating a business requirement into SQL.
Exercise 8: Calculate Order Totals
Task: Show each order ID, customer name, and total value. Calculate each line as quantity multiplied by the stored unit price.
Solution:
SELECT o.order_id,
c.customer_name,
SUM(oi.quantity * oi.unit_price) AS order_total
FROM orders AS o
JOIN customers AS c ON c.customer_id = o.customer_id
JOIN order_items AS oi ON oi.order_id = o.order_id
GROUP BY o.order_id, c.customer_name
ORDER BY o.order_id;
Expected result: (101, Alice, 50.00), (102, Alice, 30.00), (103, Bob, 80.00), (104, Cara, 50.00), and (105, Cara, 30.00).
Order 101 has two item rows: two keyboards at 20.00 and one mouse at 10.00. Summing line values produces 50.00. The query groups at the order grain; it does not sum an order-level amount once per item. If you later join another one-to-many table, aggregate each relationship separately before combining them to avoid multiplying values. Because this solution uses an inner join to items, an order with no items would be excluded.
Exercise 9: Find Matching Customers with a Subquery
Task: Find customers who have placed at least one order on 2025-01-02. Return each customer once.
Solution:
SELECT c.customer_id, c.customer_name
FROM customers AS c
WHERE c.customer_id IN (
SELECT o.customer_id
FROM orders AS o
WHERE o.order_date = DATE '2025-01-02'
)
ORDER BY c.customer_id;
Expected result: (1, Alice) and (3, Cara).
The subquery identifies customer IDs associated with orders on the requested date. The outer query returns matching customers once because it reads from the customer table, rather than producing a row for each matching order. EXISTS is another useful approach; compare both forms using additional test data before assuming they are interchangeable for every requirement.
Advanced SQL Window Function Exercises with Solutions
Window functions calculate values across related rows without necessarily collapsing those rows into a single aggregate. A common table expression, or CTE, can first establish the correct grain and then make a ranking or comparison easier to read.
Pay attention to the difference between the ordering inside OVER, which controls the calculation, and the final ORDER BY, which controls presentation. When rows share a date, a stable secondary key is essential if the task requires a specific sequence or exactly one selected row.
Exercise 10: Rank Customers by Spending
Task: Calculate total spending for customers with orders and assign a spending rank. Customers with the same total must share the same rank.
Solution:
WITH customer_spending AS (
SELECT c.customer_id,
c.customer_name,
SUM(oi.quantity * oi.unit_price) AS total_spent
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
JOIN order_items AS oi ON oi.order_id = o.order_id
GROUP BY c.customer_id, c.customer_name
)
SELECT customer_id,
customer_name,
total_spent,
DENSE_RANK() OVER (ORDER BY total_spent DESC) AS spending_rank
FROM customer_spending
ORDER BY spending_rank, customer_id;
Expected result: (1, Alice, 80.00, 1), (2, Bob, 80.00, 1), and (3, Cara, 80.00, 1).
The CTE creates one row per customer before ranking. DENSE_RANK assigns the same rank to equal totals and does not leave a gap after a tie. Do not add customer ID to the window ordering if ties on spending must remain ties; use it only in the final ordering for stable display. Customers without orders are excluded by the inner joins.
Exercise 11: Calculate a Running Total
Task: Calculate each order total and the cumulative value of all orders in chronological order. Use order ID to break date ties.
Solution:
WITH order_totals AS (
SELECT o.order_id,
o.order_date,
SUM(oi.quantity * oi.unit_price) AS order_total
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id
GROUP BY o.order_id, o.order_date
)
SELECT order_id,
order_date,
order_total,
SUM(order_total) OVER (
ORDER BY order_date, order_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM order_totals
ORDER BY order_date, order_id;
Expected result: (101, 2025-01-01, 50.00, 50.00), (103, 2025-01-01, 80.00, 130.00), (102, 2025-01-02, 30.00, 160.00), (104, 2025-01-02, 50.00, 210.00), and (105, 2025-01-03, 30.00, 240.00).
The CTE prevents the running calculation from operating on individual item rows. The explicit ROWS frame adds rows from the start of the ordered result through the current row. There is no PARTITION BY, so the running total covers all customers; add a customer partition if the requirement changes to a separate running total per customer.
Exercise 12: Find Each Customer’s Latest Order
Task: Return exactly one latest order for each customer who has orders. If a customer has multiple orders on the latest date, choose the highest order ID.
Solution:
WITH ranked_orders AS (
SELECT o.customer_id,
o.order_id,
o.order_date,
ROW_NUMBER() OVER (
PARTITION BY o.customer_id
ORDER BY o.order_date DESC, o.order_id DESC
) AS row_num
FROM orders AS o
)
SELECT customer_id, order_id, order_date
FROM ranked_orders
WHERE row_num = 1
ORDER BY customer_id;
Expected result: (1, 102, 2025-01-02), (2, 103, 2025-01-01), and (3, 105, 2025-01-03).
PARTITION BY restarts numbering for each customer. ROW_NUMBER assigns exactly one row number 1 per nonempty partition, and the descending order ID makes the selection deterministic when dates tie. To return every order tied on the latest date instead, use a ranking approach based on the date alone and adjust the requirement accordingly.
Exercise 13: Compare Orders with the Previous Order Using LAG
Task: For each order, show its total, the same customer's previous order total, and the difference from that previous total. Order a customer's orders by date and then ID.
Solution:
WITH order_totals AS (
SELECT o.customer_id,
o.order_id,
o.order_date,
SUM(oi.quantity * oi.unit_price) AS order_total
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id
GROUP BY o.customer_id, o.order_id, o.order_date
), compared AS (
SELECT customer_id,
order_id,
order_date,
order_total,
LAG(order_total) OVER (
PARTITION BY customer_id
ORDER BY order_date, order_id
) AS previous_total
FROM order_totals
)
SELECT customer_id, order_id, order_date, order_total,
previous_total,
order_total - previous_total AS difference
FROM compared
ORDER BY customer_id, order_date, order_id;
Expected result: (1, 101, 2025-01-01, 50.00, NULL, NULL), (1, 102, 2025-01-02, 30.00, 50.00, -20.00), (2, 103, 2025-01-01, 80.00, NULL, NULL), (3, 104, 2025-01-02, 50.00, NULL, NULL), and (3, 105, 2025-01-03, 30.00, 50.00, -20.00).
LAG reads the preceding row within each customer's ordered partition. The first order has no preceding row, so its previous total and difference are null. Replacing that null with zero would be a separate business decision: it would represent the first order as a change from zero rather than as an order with no comparison.
Common SQL Mistakes and How to Debug Queries
When a query produces an unexpected answer, reduce it to smaller steps. First check the source rows, then inspect the join output, and only then add grouping or window calculations. Compare row counts at each stage and write down the grain you expect: for example, five orders versus seven order-item rows.
Unexpected Duplicates and Missing Rows
Inspect identifiers before aggregating. The following diagnostic query shows which item rows contribute to each order:
SELECT o.order_id, oi.order_item_id, oi.quantity, oi.unit_price
FROM orders AS o
LEFT JOIN order_items AS oi ON oi.order_id = o.order_id
ORDER BY o.order_id, oi.order_item_id;
If an order appears multiple times, determine whether those rows represent legitimate items or an unintended join multiplication. Also check whether an inner join removes unmatched records. With a left join, a right-table filter in WHERE, such as WHERE o.order_date = DATE '2025-01-02', excludes null-extended rows and therefore removes customers without matching orders. Put a matching restriction in ON when you need to retain all left-side rows, and verify that this matches the intended semantics.
NULLs, Aggregates and Window Function Pitfalls
After a left join, COUNT(*) counts the null-extended row for a customer with no orders; COUNT(o.order_id) counts only actual matching orders. For window functions, inspect partitions, tie-breakers, and frames rather than assuming that final display order defines the calculation.
Test an empty result, missing values, same-date orders, customers without orders, and ties in totals. If your production model permits orders with no items, test those too: several solutions in this guide intentionally exclude them through inner joins. Small edge-case fixtures are especially valuable when validating reports or automated data checks.
Build a Consistent SQL Practice Routine
Practice is more useful when you revisit the same problem with changed assumptions. Solve an exercise without looking at its solution, record the result you expect, and then run your query. When the output differs, explain whether the issue is filtering, join cardinality, aggregation, null handling, or ordering.
Revisit Exercises and Change the Requirements
Add a second order for Alice on the same date and verify the latest-order tie-breaker. Add an order with no items and decide whether totals should exclude it or display zero. Compare a subquery with an equivalent join or EXISTS query, checking both ordinary cases and edge cases rather than relying on a single matching output.
Apply SQL Practice to a Real QA Scenario
Imagine testing an order confirmation feature. First identify the expected customer and order, then inspect the associated item rows and calculate their total using the stored prices. Check that a customer without an order is not accidentally included in an inner-join report. Finally, add a same-date order to verify that a latest-order query follows the product's tie-breaking rule.
Keep test data separate from production data and record assumptions alongside expected results. A query can return the right value for the sample fixture yet fail when an order has multiple items or a customer has no matching record.
Continue with 100 SQL Practice Exercises
For a next step, explore the course 100 SQL Practice Exercises with Solutions at https://rafalpodraza.com/en/courses/100-sql-practice-exercises-with-solutions. You can also keep a personal collection of requirements, test data, queries, and expected results. Repeating exercises after a break helps you identify concepts you understand independently rather than only recognize in a worked example.
SQL Practice Exercises with Solutions: FAQ
How Do I Practice SQL as a Beginner?
Choose one SQL dialect, create a small dataset, and begin with selection, filtering, sorting, and grouping. Write each query before reviewing a solution, then modify the data to include missing values and unmatched records. Progress to joins and window functions once you can explain the results of the simpler queries.
Which SQL Dialect Should I Learn First?
PostgreSQL is a practical choice for these exercises because every example uses it consistently. If your workplace or target role uses another database, practicing in that system can also be useful. Core concepts transfer, but syntax and behavior vary, so consult the documentation for the database you actually use.
How Do I Know Whether My SQL Solution Is Correct?
Compare the rows, values, ordering requirements, and edge-case behavior against the task. Different query text can produce the same correct result, while two queries that match on a small fixture may diverge when there are ties, nulls, or multiple matching rows. Add targeted test data and verify the intended result grain.
What Is the Difference Between WHERE and HAVING?
WHERE filters source rows before grouping, whereas HAVING filters groups after aggregate values are calculated. For example, filter the order date in WHERE to count only orders from that date, then use HAVING to keep customers whose resulting count exceeds a threshold.
Why Does a LEFT JOIN Return More Rows Than Expected?
A left-side row appears once for each matching right-side row. A customer with two orders therefore produces two joined rows; a customer with no orders produces one null-extended row. Check the relationship and intended result grain before using aggregation or DISTINCT to change the output.
Are These Exercises Useful for SQL Interviews?
They provide practice with common patterns such as joins, aggregation, subqueries, ranking, and running totals. Explain your assumptions and how you handle ties or missing data, not just the final syntax. Interview expectations and permitted SQL dialects vary, so adapt your preparation to the role and the database involved.
Key Takeaways
- Start with a consistent PostgreSQL dataset and predict results before running each query.
- Define the result grain before joining or aggregating, and inspect intermediate rows when counts change unexpectedly.
- Use IS NULL for missing values, HAVING for aggregate filters, and explicit ordering when results must be deterministic.
- Build order-level totals before applying window calculations, and specify partitions, tie-breakers, and frames deliberately.
- Validate solutions with customers without orders, same-date orders, tied totals, and other cases relevant to your application.