Querydrill

SQL HAVING practice problems

WHERE filters rows before they are grouped, HAVING filters the groups afterwards. Questions that say more than three orders, at least two customers or a total above a threshold are HAVING questions.

Each problem here needs a condition on an aggregate, and several need both a WHERE and a HAVING in the same query, which is the combination interviewers like to ask about.

Try one here: Repeat buyers

Try it yourself

Return the customer_id of every customer who placed more than two orders, whatever the status.

orders (first 12 of 14 rows)

idcustomer_idorder_dateamountstatus
10112025-01-03120paid
10212025-01-2080.5paid
10322025-01-22200paid
10432025-02-0245refunded
10532025-02-15310paid
10642025-02-18150pending
10752025-03-0160paid
10862025-03-0995paid
10962025-03-30130paid
11062025-04-1175paid
11172025-04-12210paid
11212025-04-2540paid

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

Aggregation

  • 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.
  • 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.

Joins

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.

Work mode

  • 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.
  • 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.

Case studies

  • 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.