Querydrill

SQL GROUP BY practice problems

GROUP BY turns rows into one line per group: orders per customer, revenue per month, headcount per department. The rule to practice is simple and strict: every selected column is either in GROUP BY or inside an aggregate.

The problems move from one grouping column to several, then to grouping on an expression such as a month, and to filtering groups with HAVING.

Try one here: Customers per country

Try it yourself

For each country, return the country and how many customers it has.

customers (8 rows)

idnamecountrysignup_date
1AnnaNL2024-01-05
2BrunoBR2024-02-11
3ChloeUS2024-03-02
4DevIN2024-03-19
5ElifTR2024-05-27
6FarahUS2024-06-14
7GusNL2024-08-01
8HanaJP2024-09-09

Free, no account needed. PostgreSQL runs in your browser and your answer is checked again on changed data.

Aggregation

  • Customers per countryFor each country, return the country and how many customers it has.
  • Spend per customerFor each customer_id, return the customer_id and the total amount of their paid orders. Customers without paid orders do not appear.
  • Repeat buyersReturn the customer_id of every customer who placed more than two orders, whatever the status.
  • Customers over a spending thresholdReturn the customer_id and the total paid amount of every customer whose paid orders add up to more than 300.
  • Revenue by monthReturn each month as text like 2025-01 together with the total of its paid orders. In PostgreSQL, to_char(order_date, 'YYYY-MM') gives the month.
  • Average salary per departmentFor each dept_id, return the dept_id and the average salary. Leave out employees without a department.
  • Orders per statusReturn each order status and how many orders have it.
  • Products per categoryReturn each product category and how many products it has.
  • Units sold per productFor each product_id, return the product_id and the total quantity sold, across all orders.
  • Hires per yearReturn each hire year (like 2021) and how many employees were hired that year. EXTRACT(YEAR FROM hire_date) gives the year.
  • Active in several monthsFor customers who ordered in at least two different months, return the customer_id and the number of different months they ordered in. Count every order, whatever the status.
  • Paid and refunded per customerFor each customer_id that has orders, return the customer_id, the number of paid orders and the number of refunded orders, in that order. A customer with no refunds shows 0.
  • Salary bandsPut every employee in a salary band: junior below 70,000, mid from 70,000 up to but not including 100,000, senior at 100,000 or more. Return each band name and how many employees are in it.
  • Paid revenue per quarterReturn each quarter as text like 2025-Q1 together with its paid revenue. January to March is Q1, April to June is Q2, and so on. In PostgreSQL, to_char(order_date, 'Q') gives the quarter number.
  • Several counts in one pass (FILTER)For each customer_id that has orders, return the customer_id, the number of orders, the number of paid orders and the total amount of the paid orders, in that order. A customer with no paid orders shows 0 for both.
  • Paid revenue per week (date_trunc)Return the first day (Monday) of each week that has paid orders, as a date, together with the paid revenue of that week.
  • Orders per weekday (EXTRACT)Return the ISO weekday number (1 for Monday to 7 for Sunday) and the number of orders placed on that weekday, whatever the status. Only weekdays that have orders.
  • 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

  • Revenue per countryReturn each country with the total of its customers' paid orders. Countries without paid orders do not appear.
  • 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).
  • 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.
  • Products per orderFor each order_id that has order lines, return the order_id and how many different products it contains.
  • 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.
  • 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.

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.
  • Share of revenueFor each country, return the country and its share of total paid revenue in percent, rounded to 1 decimal.
  • Month over monthReturn each month (like 2025-01), its paid revenue, and the change from the previous month's paid revenue. The first month shows NULL for the change.
  • 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.
  • 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.
  • 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

  • Departments above averageReturn the dept_id and average salary of every department whose average salary is above the average salary of all employees. Ignore employees without a department when grouping.
  • Repeat purchase rateOf all customers who placed at least one order, what percentage placed two or more orders, whatever the status? Return a single number rounded to 1 decimal.
  • Runs of the same statusGo through the orders by id and group consecutive orders that share the same status into runs. For each run, return the status, the first order id, the last order id and the number of orders in the run.
  • 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.
  • 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.
  • Daily active usersReturn every day that has events, as a date, with the number of different users who were active on that day.
  • Monthly active usersReturn every month that has events, as text in the form YYYY-MM, with the number of different users who were active in that month.
  • 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.
  • Sessions per user (30-minute rule)A new session starts with a user's first event, and again whenever more than 30 minutes have passed since that user's previous event. Return each user_id with their number of sessions.
  • 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).
  • Longest streak of active daysReturn each user_id with the length of their longest run of consecutive active days. A user who was never active two days in a row has a streak of 1.
  • Merge bookings into occupied periodsFor each room, merge bookings that overlap or touch (one ends on the day the next starts) into one occupied period. Return the room, the first check_in and the last check_out of every period.

Work mode

  • Clean up the country reportFrom Marta in Marketing: "Our country report shows US, us and ' Us' as three different countries. Send me each country once, in capitals with no spaces around it, with the number of signups. Leave out signups that have no country." Return two columns: country and signups.
  • Find duplicate accountsFrom Sam in Support: "Some people signed up more than once with the same email, typed differently (capitals, extra spaces). List each email that has more than one account, in lowercase with no spaces, and how many accounts it has. Most accounts first, then alphabetically." Return email and accounts.
  • Monthly revenue from mixed datesFrom Priya again: "Same paid revenue, but by month please, oldest month first. Careful: paid_at comes in three formats." Return month as YYYY-MM and revenue rounded to 2 decimals.
  • Signups per planFrom Leo in Product: "How many signups are on each plan? Write the plan names in lowercase, and count signups without a plan as unknown." Return plan and signups.
  • 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.
  • Failed payments by monthFrom Priya in Finance: "How many payments failed each month, and how much money is that? Status capitals and spaces vary, and the amounts are text like $1,200.00. Oldest month first." Return month as YYYY-MM, failed (a count) and amount rounded to 2 decimals.
  • 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

  • Revenue report, step 1: revenue per monthYou are building the monthly revenue report. Start with the base: for each month that has paid orders, return the month as YYYY-MM and the total paid amount, in columns month and revenue.
  • Revenue report, step 2: change on the previous monthExtend the monthly report. For each month return month, revenue, the previous month's revenue as prev_revenue, and the difference as change (revenue minus prev_revenue). The first month has no previous month, so both extra columns are NULL there.
  • Revenue report, step 3: running totalAdd a year-to-date column. For each month return month, revenue and running_total: the sum of paid revenue from the first month up to and including that month.
  • Revenue report, step 4: share of the totalFinish the report. For each month return month, revenue and share_pct: that month's percentage of all paid revenue, rounded to 1 decimal.
  • 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.
  • Refund review, step 1: refund rate per monthThe head of sales thinks refunds are getting out of hand and wants facts by Friday. Start with the trend: for every month that has orders, return the month as text like 2025-01, the number of orders, the number of refunded orders and the refund rate in percent, rounded to 1 decimal. Count every order, whatever its status, in the number of orders.
  • 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 4: hires per year and running headcountHow did the team grow? For every year in which someone was hired, return the year as a number, the number of hires in that year and the running total of hires up to and including that year.
  • 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.