Skip to main content

You join an orders table to a payments table on order_id to report revenue, and the total is too high because the row count grew. Explain why and fix it. For example, an order of 100 that was paid in two parts appears twice, so its amount is counted as 200.

Coding rounds · Intermediate 2

Short answer

The join key is not unique on one side. An order with two payments matches twice, so SUM counts its amount twice. Confirm with GROUP BY order_id HAVING COUNT(*) > 1 on payments. Fix it by aggregating payments to one row per order in a subquery before the join, which costs one extra GROUP BY. Do not add DISTINCT afterwards.

Deeper answer

First clarify the grain of each table: what one row means. Orders has one row per order. Ask whether payments has one row per order or one per payment attempt. A join returns one row for every matching pair, so a one-to-many relationship repeats the row on the one side.

Prove it before fixing it. Run SELECT order_id, COUNT(*) FROM payments GROUP BY order_id HAVING COUNT(*) > 1 to find keys that repeat, and compare COUNT(*) before and after the join. Then fix the grain: join orders to (SELECT order_id, SUM(paid) AS paid FROM payments GROUP BY order_id) so the right side has one row per order.

Do not hide the problem with SELECT DISTINCT or SUM(DISTINCT amount). DISTINCT on amounts merges two different orders that have the same amount, so the total becomes too low. Test with an order paid in two parts and an order with no payment, which needs a LEFT JOIN to stay in the report. Say that a missing join condition, such as a second key column, causes the same symptom.

What a strong answer covers

Answer it out loud in the mock interview about 2.5 min

Follow-ups to expect

Common mistakes

Learn it

SQL for engineers

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.