Find Orders with More Than One Payment Record
Return the orders that have two or more rows in the payments table.
The challenge runs on the SQLabHub practice database (SQLite) and uses the payments table. You can solve it in the browser, with nothing to install.
The task
Find orders that have more than one payment record.
A correct answer returns 59 rows with one column: order_id.
Tables used in this challenge
payments 200 rows
id INTEGER (PK) · order_id INTEGER · user_id INTEGER · amount REAL · method TEXT · status TEXT · paid_at TEXT · transaction_id TEXT
| id | order_id | user_id | amount | method | status | paid_at | transaction_id |
|---|---|---|---|---|---|---|---|
The first rows of each table are shown. See how all the tables relate on the database schema page.
Expected output
| order_id |
|---|
First 5 of 59 rows. This is the output of the model solution on the practice database. The task does not fix a sort order, so your rows may come back in a different order.
What you practise
- Summarising many rows into one value with COUNT, SUM, AVG, MIN or MAX
- Grouping rows with GROUP BY to get one result row per group
- Filtering groups after aggregation with HAVING
Hint and approach
Try the challenge first. Open these only when you need them.
Show the hint
GROUP BY order_id HAVING COUNT
Show the step-by-step approach
How the model solution is built, in the order the database evaluates it:
- Read from the
paymentstable. - Group the rows by
order_id, so the result has one row for each value. - For each group, compute
COUNT(*). - Filter the groups in
HAVING: keep those whereCOUNT(*)is greater than 1.
Model solution
Checking your session…
What to watch for
Group by the key and keep the groups with a count above 1. The same query finds duplicate emails, invoice numbers or any other value that should be unique.
- HAVING. Conditions on single rows belong in WHERE and conditions on aggregates in HAVING. Putting a row filter in HAVING works, but it groups rows that are about to be thrown away.
- GROUP BY. Every selected column must either be in GROUP BY or sit inside an aggregate. SQLite accepts other columns and returns an arbitrary value for them; most databases raise an error.
- Aggregate functions. Aggregates skip NULLs. AVG divides by the number of non-NULL values and COUNT(column) can be smaller than COUNT(*).
Related SQL challenges
- Find Churned Customers with No Orders in the Last 90 DaysSimilar levelHard
- Find Managers Who Earn More Than All Their Direct ReportsSimilar levelHard
- Find Customers with More Than 3 Orders Using HAVINGEasierMedium
- Find Orders with More Than 3 Items Using HAVING SUMEasierMedium
- Find Products with an Average Rating Above 4EasierMedium
Keep learning
- Lesson: HAVING Clause
- Lesson: GROUP BY
- Lesson: Aggregate Functions
- All SQL practice challenges, by difficulty and topic
- SQL interview questions with answers
- SQL Playground: run any query on the same database