SQL JOIN practice problems
Joins are where most SQL mistakes happen: a missing ON condition multiplies rows, an inner join silently drops the customers with no orders, and a filter in the wrong place turns a LEFT JOIN back into an inner one.
These problems start with two tables and one key and work up to three-table joins, self joins and joins on a cleaned-up key. Each answer is checked on the rows you see and again on changed data, so a join that only happens to work today does not pass.
Try one here: Subtotals and a grand total (ROLLUP)
Try it yourself
Return the paid revenue per country and, in the same result, one extra row with the total over all countries. The total row shows NULL as the country.
customers (8 rows)
| id | name | country | signup_date |
|---|---|---|---|
| 1 | Anna | NL | 2024-01-05 |
| 2 | Bruno | BR | 2024-02-11 |
| 3 | Chloe | US | 2024-03-02 |
| 4 | Dev | IN | 2024-03-19 |
| 5 | Elif | TR | 2024-05-27 |
| 6 | Farah | US | 2024-06-14 |
| 7 | Gus | NL | 2024-08-01 |
| 8 | Hana | JP | 2024-09-09 |
orders (first 12 of 14 rows)
| id | customer_id | order_date | amount | status |
|---|---|---|---|---|
| 101 | 1 | 2025-01-03 | 120 | paid |
| 102 | 1 | 2025-01-20 | 80.5 | paid |
| 103 | 2 | 2025-01-22 | 200 | paid |
| 104 | 3 | 2025-02-02 | 45 | refunded |
| 105 | 3 | 2025-02-15 | 310 | paid |
| 106 | 4 | 2025-02-18 | 150 | pending |
| 107 | 5 | 2025-03-01 | 60 | paid |
| 108 | 6 | 2025-03-09 | 95 | paid |
| 109 | 6 | 2025-03-30 | 130 | paid |
| 110 | 6 | 2025-04-11 | 75 | paid |
| 111 | 7 | 2025-04-12 | 210 | paid |
| 112 | 1 | 2025-04-25 | 40 | paid |
Free, no account needed. PostgreSQL runs in your browser and your answer is checked again on changed data.
Aggregation
- Subtotals and a grand total (ROLLUP)Return the paid revenue per country and, in the same result, one extra row with the total over all countries. The total row shows NULL as the country.
Joins
- Orders with customer namesReturn one row per order: the order id, the customer name and the amount.
- Customers who never orderedReturn the names of customers who have no orders at all.
- Revenue per countryReturn each country with the total of its customers' paid orders. Countries without paid orders do not appear.
- Everyone with a departmentReturn every employee's name and department name. Employees without a department must still appear, with NULL as the department name.
- Employee and managerReturn each employee's name and their manager's name. Employees without a manager show NULL.
- Revenue per productUsing order lines, return each product name with its revenue: quantity times price, summed over all its order lines. Products never sold do not appear.
- Revenue per categoryReturn each product category with its revenue from order lines (quantity times price).
- Products never soldReturn the names of products that appear on no order line.
- Headcount per departmentReturn every department name and its number of employees. Departments with no employees must show 0.
- Orders per customerReturn every customer name with the number of orders they placed, including customers with 0 orders.
- Most recent order per customerReturn every customer's name and the date of their most recent order, whatever the status. Customers who never ordered must still appear, with NULL as the date.
- Customers from the same countryReturn each pair of customer names that share a country, listing every pair once with the lower customer id first.
- Categories per customerFor each customer who placed at least one order, return the customer name and the number of different product categories they have bought from, across all their orders whatever the status.
- Payroll per departmentReturn every department name with the total salary of its employees. Departments with no employees must show 0, not NULL.
- Direct reports per managerReturn each manager's name and how many employees report directly to them. Only employees who manage at least one person appear.
- Keep both sides with a full joinReturn every employee name with their department name. Keep employees without a department and also departments without employees; the missing side shows NULL. In the sample data every department has staff, but your query must still handle an empty department.
- Products on each order as one text (string_agg)For each order that has order lines, return the order_id and the names of its products as one text, separated by a comma and a space, in alphabetical order. A product listed twice on an order appears once.
- Customers whose every order is paid (bool_and)Return the names of customers who have at least one order and whose orders all have the status paid.
- Revenue inflated by a join (fan-out)For each customer with at least one paid order (status paid), return the name, the total amount of their paid orders and the total quantity of items on those orders. An order without item lines counts with quantity 0. Customer names are unique.
- Not equal, and the rows with NULLReturn the names of all employees who do not work in the Engineering department. Employees with no department count too.
- Overlapping bookingsA booking occupies its room from check_in up to, but not including, check_out. Return every pair of bookings for the same room that overlap, as two ids with the lower id first. A booking that starts on the day another one ends does not overlap it.
Advanced
- Big spendersCalculate each customer's total paid spend, then return the names of customers whose total is above the average of those totals. Only customers with at least one paid order count in the average.
- Levels in the reporting chainReturn each employee's name and their level in the reporting chain: 1 for employees without a manager, 2 for the people who report to them, 3 for the level below that, and so on.
- Share of revenueFor each country, return the country and its share of total paid revenue in percent, rounded to 1 decimal.
- Top two per categoryFor each category, return the category, product name and revenue (quantity times price) of its two best-selling products by revenue.
- Cumulative share of revenueReturn each sold product with its revenue (quantity times price) and the cumulative share of total revenue in percent, rounded to 1 decimal, going from the product with the most revenue to the least. Order by revenue descending, then by product name. The last row shows 100.
- Two largest paid orders per customer (LATERAL)For each customer with paid orders, return the customer's name and the id and amount of their two largest paid orders (highest amount first, then lowest id). A customer with one paid order returns one row.
- Most orders, ties includedWhich customers placed the most orders, counting orders of every status? Return the name and the number of orders of every customer who shares first place. Customer names are unique.
- Year-over-year growthFor every month of 2025 that is in the table, return the month, its revenue, the revenue of the same month one year earlier, and the growth as a percentage rounded to 1 decimal. When there is no figure for the same month a year earlier, the last two columns are NULL. When that figure is 0, the growth is NULL.
- Price at the time of the orderprice_history holds the price of a product from each valid_from date onward. For every order line of a product that has a price on the order date, return the order id, the product id and the price that was valid on the order date. A price counts from its valid_from date itself.
- One row per array elementSome payloads carry a JSON array called tags, and a tag appears at most once in a payload. Return every tag with the number of webhooks that carry it.
Interview classics
- Earns more than the managerReturn the names of employees who earn more than their own manager.
- Orders in consecutive monthsReturn the customer_id of every customer who placed orders in two calendar months in a row, for example March and April, whatever the status. Each customer appears once.
- Cohort retentionGroup customers by the month of their first order, like 2025-01, counting every order whatever the status. For each such month return the month, the number of customers who first ordered in it, and how many of those customers ordered again in a later month.
- Products bought togetherReturn every pair of products that appear together on the same order: the first product name, the second product name and the number of orders that contain both. List each pair once, with the lower product id first.
- First order not paidReturn the names of customers whose first order (earliest date, then lowest id) has a status other than paid.
- A month with no sales still shows up (generate_series)Return every month from January to June 2025 as text like 2025-01, with its paid revenue. A month without paid orders must still appear, with 0.
- Signup to purchase conversionA user converted when they have a purchase that is later than their first signup. Return one row: the number of users who signed up, the number of those who converted, and the conversion rate as a percentage rounded to 1 decimal.
- New and returning users per dayA user is new on the first day they have any event and returning on every later day they are active. Return every day that has events, as a date, with the number of new users and the number of returning users on that day.
- Day-1 retentionA user is retained on day 1 when they have an event on the calendar day right after their first active day. Every user counts in the total, also a user whose first day is the last day in the data. Return one row: the number of users, the number retained on day 1, and the retention rate as a percentage rounded to 1 decimal.
- Retention curveFor each number of days since a user's first active day, from 0 to 7, return that number and how many users were active that many days after their first day. Day 0 is the first day itself. Leave out day numbers on which nobody was active.
- Rolling 7-day active usersFor every day that has events, return the day, as a date, and the number of different users with an event in the 7 days ending on that day (that day and the 6 days before it).
- Monthly churn rateA user is active on a day when one of their subscriptions started on or before that day and has no end date or an end date after that day. Return one row for March 2025: the number of users active on 2025-03-01, how many of them were no longer active on 2025-04-01, and that share as a percentage rounded to 1 decimal.
Work mode
- Paying customers by countryFrom Marta: "For each country, cleaned as before, how many different people made at least one paid payment? Count a person once even if they have several accounts. Most payers first, then by country." Return country and payers.
- First payment per customerFrom Sam: "For each customer who paid at least once, what was the date of their first paid payment? One row per email, cleaned to lowercase, oldest first, then by email." Return email and first_paid as YYYY-MM-DD.
- Revenue per planFrom Leo in Product: "What is our paid revenue per plan? Plan names arrive in any capitals, and some signups have no plan: call those unknown. Amounts are text, and a payment is paid whatever the capitals or spaces in its status." Return plan and revenue rounded to 2 decimals.
- Signed up, never paidFrom Marta in Marketing: "Which people signed up but never made a paid payment? Treat emails as the same person whatever the capitals or spaces, and count a person as paid if any of their accounts has a paid payment. One row per email, in lowercase." Return email.
- Days from signup to first paymentFrom Leo: "For each signup that has a paid payment, how many days passed between the signup and the first paid payment? Both dates come in mixed formats: a plain date, a date with a time, or a date with a T and a time." Return the signup id and the number of days as a whole number.
Case studies
- Customer value, step 1: orders and spend per customerYou are sizing up the customer base. For every customer with at least one paid order, return name, the number of paid orders as orders, and their total paid amount as total.
- Customer value, step 2: first order, last order, days activeFor every customer with at least one paid order, return name, the date of their first paid order as first_order, their last paid order as last_order, and days_active: the whole number of days between the two (0 for a single order).
- Customer value, step 3: segment the customersLabel each customer with at least one paid order. Return name, total (their paid spend) and segment: 'high' for 400 or more, 'mid' for 150 or more, otherwise 'low'.
- Customer value, step 4: summarize the segmentsRoll the segments up. For each segment from step 3 return segment, the number of customers in it as customers, and their combined paid spend as revenue.
- Product performance, step 1: units and revenue per productYou are reviewing the catalog. For every product sold in at least one paid order, return name, total quantity sold as units, and revenue (quantity times price), counting paid orders only.
- Product performance, step 2: revenue per categoryRoll product revenue up to categories. For each category with paid sales, return category, units and revenue, counting paid orders only.
- Product performance, step 3: best seller in each categoryFor each category, return category, name and revenue of the product with the highest paid revenue in that category.
- Product performance, step 4: products with no paid salesClose the review with the dead stock. Return the name of every product that has never been part of a paid order.
- Refund review, step 2: refund rate per countryNext question from the head of sales: is it one market? For every country that has orders, return the country, the number of orders, the number of refunded orders and the refund rate in percent, rounded to 1 decimal.
- Refund review, step 3: who gets the refundsIs it a few customers? For every customer with at least one refunded order, return the name, the number of refunded orders, the refunded amount and that customer's share of the total refunded amount in percent, rounded to 1 decimal.
- Refund review, step 4: refunded value per categoryIs it a product problem? For every product category, return the category and the value of its order lines (quantity times price) on refunded orders. A category with nothing refunded must still appear, with 0.
- Payroll review, step 1: headcount and payroll per departmentFinance is preparing next year's budget and asks for the people numbers. Start with the base table: for every department, return the department name, the number of employees and the total salary. A department with no employees must still appear, with 0 and 0.
- Payroll review, step 2: pay against the company averageWhich departments pay above the company average? For every department that has employees, return the department name, its average salary rounded to a whole number, and the difference between that average and the average salary of all employees, also rounded to a whole number. All employees means everyone, including those without a department.
- Payroll review, step 3: the top earner's shareHow concentrated is the pay? For each department, return the department name, the name of its highest-paid employee and that salary as a percentage of the department's total salary, rounded to 1 decimal. If several employees share the top salary, return each of them.
- Payroll review, step 5: managers and their teamsClose the review with the span of control. For every manager with at least two direct reports, return the manager's name, the number of direct reports, the total salary of those reports and their average salary rounded to a whole number.
Read first if you are stuck
Other practice sets
Your first 8 exercises are free, with no account. Every answer is checked on the rows you see and again on changed data.