SQL practice exercises: 161 tasks from SELECT to window functions, checked as you go
Good SQL practice exercises have three things in common: real tables, a checker that tells you whether your rows are right, and a difficulty curve that starts at SELECT and ends somewhere past window functions. This page walks through that curve. Each section explains the idea, shows one worked query you can run anywhere, and lists the exercises on Querydrill that practice it on a live PostgreSQL database in your browser.
What makes SQL practice exercises worth doing
Reading about joins does not make you able to write one under time pressure. The exercises below use a small sample schema that behaves like a real one: departments, employees (with a manager_id that points back at employees), customers, orders, products and order_items, plus two raw tables full of inconsistent text and dates for the cleaning exercises. Every answer is checked twice, once on the tables you can see and once on a hidden copy with extra rows, so a query that only works by coincidence fails.
The levels run from 0 to 5. Level 0 is column picking and filtering, level 1 is aggregation, level 2 is joins, level 3 is subqueries, CTEs and window functions, level 4 combines them, and level 5 is work mode, where the data arrives messy and the question comes from a colleague rather than a textbook. If you can already write a GROUP BY without thinking, start at level 2.
Beginner SQL practice exercises: SELECT, WHERE, ORDER BY, LIMIT
The first level is about reading a question and turning it into the four clauses that make up most queries. Pick columns, filter rows, sort, and cut the list. The worked example returns the highest earners above a threshold, highest first:
SELECT name, salary FROM employees WHERE salary > 90000 ORDER BY salary DESC;
On the sample data that returns Ava, Ben, Gia and Finn. Two details trip people up at this level. Text comparisons need single quotes (status = 'paid'), and LIMIT without ORDER BY returns an arbitrary set of rows, so the top three only means something once the rows are sorted. The CASE exercise at the end of this level is where you first write a calculated column, which comes back constantly later.
- Pick two columns
- Filter rows
- Top three earners
- Count paid orders
- Each country once
- Two countries
- Pattern match
- No manager
- Sort on two columns
- Label with CASE
If any clause here is new, the pages at /sql-tutorial/where and /sql-tutorial/order-by give the syntax, the usual mistakes and more runnable examples before you attempt the drills.
GROUP BY and HAVING exercises
Aggregation is where SQL starts to replace a pivot table. The pattern is always the same: choose the column that defines the groups, aggregate the rest, and put any condition on the aggregate in HAVING rather than WHERE. This query finds countries with more than one customer:
SELECT country, COUNT(*) AS customers FROM customers GROUP BY country HAVING COUNT(*) > 1;
It returns NL and US, two each. The exercises at this level cover counts per group, sums per customer, averages per department, revenue by month (using to_char(order_date, 'YYYY-MM') in PostgreSQL, or strftime in SQLite), and COUNT(DISTINCT ...) for the number of customers who ordered rather than the number of orders. The hidden-data check matters most here: a query that hardcodes this month's dates passes once and fails the second run.
- Customers per country
- Spend per customer
- Repeat buyers
- Revenue by month
- Average salary per department
- First and last order
- Orders per status
- Customers who ordered
- Hires per year
The reference page at /sql-tutorial/group-by explains why every non-aggregated column must appear in GROUP BY, and /sql-tutorial/having covers the WHERE versus HAVING split with examples.
SQL join practice exercises: inner, left and self joins
Joins are the level where most people's practice stalls, because the mistakes are quiet: an inner join that drops the customers with no orders, a left join whose WHERE clause turns it back into an inner join, a join on the wrong key that doubles every amount. The classic anti-join finds customers who never ordered:
SELECT c.name FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL;
On the sample data only Hana comes back. The self-join exercise pairs each employee with their manager through manager_id, and the three-table exercises join order_items to products to get revenue per product and per category. Count the rows before and after each join; if the count grew and you did not expect it to, the join key is not unique on one side.
- Orders with customer names
- Customers who never ordered
- Revenue per country
- Everyone with a department
- Employee and manager
- Revenue per product
- Revenue per category
- Products never sold
- Headcount per department
See /sql-tutorial/left-join for the full set of left join patterns, including the anti-join above, and /sql-tutorial/self-join for the employee and manager case.
Subquery, CTE and window function exercises
Level 3 is what separates a candidate who can query from one who can analyze. Subqueries answer questions that depend on another result (everyone above the average salary). CTEs break a long query into named steps that read top to bottom. Window functions compute a rank, a running total or a previous value without collapsing the rows. Ranking within a group is the one asked most often:
SELECT name, dept_id, salary, RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rank_in_dept FROM employees;
A running total uses SUM(amount) OVER (ORDER BY order_date), month over month change uses LAG, and share of revenue divides a row's total by SUM(...) OVER () with no partition. The second and third highest salary exercises are worth doing both ways, with LIMIT and OFFSET on DISTINCT salaries and with DENSE_RANK, because interviewers ask what happens when two people share the top salary.
- Above the average salary
- Rank within department
- Running revenue total
- Top earner per department
- Second highest salary
- Big spenders
- Dense rank
- Change from the previous order
- Share of revenue
The page at /sql-tutorial/window-functions is the right place to start if OVER and PARTITION BY are new; /sql-tutorial/cte-with shows how to build the level 4 exercises step by step.
Messy data exercises: SQL practice that looks like real work
Textbook tables are clean. Real exports are not: the same email typed three ways, country codes with trailing spaces, amounts stored as text with dollar signs and commas, timestamps mixed with plain dates. Level 5 is built from two such tables, signups_raw and payments_raw, and every prompt is phrased the way a colleague would ask it. Finding duplicate accounts is the typical task:
SELECT LOWER(TRIM(email)) AS email, COUNT(*) AS accounts FROM signups_raw GROUP BY LOWER(TRIM(email)) HAVING COUNT(*) > 1 ORDER BY accounts DESC, email;
Normalizing inside GROUP BY is what makes the copies match; without LOWER and TRIM the query returns nothing and the duplicates stay hidden. The revenue exercises need REPLACE to strip the currency symbols and CAST to turn the text into numbers before SUM will give a sensible answer, and the date exercises need SUBSTR or DATE() to make a plain date and a timestamp fall into the same month.
- Clean up the country report
- Find duplicate accounts
- Total revenue from text amounts
- Monthly revenue from mixed dates
- Signups per plan
- Paying customers by country
- First payment per customer
The duplicate pattern, including how to delete the copies while keeping one, is written up at /sql-tutorial/find-duplicates. Turning status rows into columns, the last level 4 exercise, is covered at /sql-tutorial/pivot.
How to practice SQL so it sticks
Write the query before you look at anything. Hints exist, but the moment of being stuck is where the learning happens; read the hint only after a real attempt. Keep sessions short and regular: twenty minutes a day for three weeks covers all 161 exercises and beats a single weekend. Redo every exercise you got wrong two days later, from a blank editor, and keep a list of the clauses that cost you an attempt.
When an exercise is solved, change the question. Ask for the bottom three instead of the top three, add a second condition to the WHERE, swap the inner join for a left join and predict the row count before running. The database resets, so nothing you break matters. Once the whole set is comfortable, the interview question list at /sql-interview-questions runs the same skills in the order a screen asks for them, and the printable summary at /sql-cheat-sheet is a one-page reminder of the syntax for the day itself.
Start the exercises, no sign-up needed
Your first 8 exercises are free, with instant checking, hints and the expected result. Pro is a one-time pass, $14.99 for 30 days with no subscription, and adds every reference solution with its explanation, timed mode and a completion certificate.
Start practicing freeQuestions
Do the SQL practice exercises come with answers?
Yes. Every exercise has a hint, the expected result, and a reference solution with an explanation. A free account can open three reference solutions a day; Pro removes the limit. Your own query is checked automatically, so you know it is right before you read the reference.
Which SQL dialect do the exercises use?
PostgreSQL, running entirely in your browser. The exercises stick to standard SQL that works the same in MySQL, SQL Server and BigQuery, including joins, CTEs and window functions. The only dialect-specific piece is date formatting, and the prompt names the PostgreSQL function when it applies.
Are the exercises suitable for complete beginners?
Level 0 starts with picking two columns from one table and assumes nothing. Each level adds one idea, and the SQL tutorial pages linked from the exercises explain the syntax from scratch. If you have never written a query, plan on the first ten exercises taking an evening.
How are my answers checked?
Your query runs against the tables shown, then again against a hidden copy of the same tables with different rows and values. Both results must match the reference. Row order is only checked when the exercise asks for a specific order. This catches queries that hardcode values or that work only on the visible data.
Can I use these exercises to prepare for a SQL interview?
Yes. The level 3 and 4 exercises (ranking within groups, second highest salary, running totals, month over month change, departments above the average) are the questions that come up most in analyst and engineer screens, and timed mode on Pro reproduces the pressure of a live test.