QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Interview tasks

Task: the top 3 users by the sum of completed deposits.

The top 3 by completed deposits comes from grouping by user, filtering type and status in WHERE, sorting the sum descending and LIMIT 3. Equal sums at the boundary are cut arbitrarily, so a second sort key is added, and RANK or WITH TIES shows all tied users. After every one-to-many JOIN the row count is watched, because sums get multiplied.

SQL · Tasks

Top 3 by deposits, and two users with the same sum share third place. Who gets shown?

The task combines almost all basic SQL: three tables, a filter by type and status, grouping, a sum, sorting and a limit. That is why interviewers watch whether the candidate keeps the order of query execution in mind and asks about equal sums. Below is a simplified sample of transactions after joining users, accounts and transactions.

usertypestatusamount
Annadepositcompleted300
Annadepositcompleted200
Annadepositfailed900
Annawithdrawalcompleted100
Bohdandepositcompleted400
Olhadepositcompleted300
Ivandepositcompleted300
Ivandepositpending50

How it works and why. First JOIN connects the rows, then WHERE drops transactions that are not completed deposits (the failed deposit of 900 and the withdrawal do not count), then GROUP BY builds the sum per user, ORDER BY sorts the groups and LIMIT takes the first three. The status filter sits in WHERE because it is a condition on a row, not on a group. The sums: Anna 500, Bohdan 400, Olha 300, Ivan 300 (the pending 50 is not included).

SELECT u.id, u.email, SUM(t.amount) AS total_deposits
FROM users u
JOIN accounts a     ON a.user_id = u.id
JOIN transactions t ON t.account_id = a.id
WHERE t.type = 'deposit' AND t.status = 'completed'
GROUP BY u.id, u.email
ORDER BY total_deposits DESC, u.id
LIMIT 3;

The same totals, two policies for ties

LIMIT 3
usertotal
Anna500
Bohdan400
Olha300
Ivan300 cut
RANK <= 3
usertotalrnk
Anna5001
Bohdan4002
Olha3003
Ivan3003
Figure 1. LIMIT 3 keeps exactly three rows, so the sort order decides which of the two with 300 gets cut. RANK returns both, because they share third place.

Example: what happens to ties. The query above returns Anna, Bohdan and Olha (Olha has a lower u.id than Ivan). Ivan has the same sum as Olha but is cut: LIMIT 3 knows nothing about equality, and the extra key u.id only makes the selection deterministic. Without it a different one of the two could stay on each run. If the requirement is to show everyone sharing third place, there are two ways.

-- 1. RANK over the totals
WITH s AS (
  SELECT u.id, u.email, SUM(t.amount) AS total_deposits
  FROM users u
  JOIN accounts a     ON a.user_id = u.id
  JOIN transactions t ON t.account_id = a.id
  WHERE t.type = 'deposit' AND t.status = 'completed'
  GROUP BY u.id, u.email
), r AS (
  SELECT *, RANK() OVER (ORDER BY total_deposits DESC) AS rnk
  FROM s
)
SELECT * FROM r WHERE rnk <= 3;

-- 2. PostgreSQL 13+: WITH TIES, no u.id in ORDER BY
-- ... ORDER BY total_deposits DESC
-- FETCH FIRST 3 ROWS WITH TIES;

WITH TIES judges equality by the ORDER BY columns: if you add u.id there, there are no ties any more and the result is three rows again. Both variants return four rows on our sample.

Limits and alternatives. Users with no completed deposit are not in the result: that follows from the INNER JOIN and the filter. To see them with zero you need a LEFT JOIN with the conditions in ON. Sums in different currencies must not be added: group by currency as well. The most dangerous case is one more join to another one-to-many table (for example the user's cards): each transaction multiplies by the number of cards and the sums come out inflated.

Common mistakes.

  • LIMIT 3 without a second sort key: with equal sums the result floats between runs.
  • No status filter: failed and pending payments get into the sum (and a condition on t.status in HAVING without an aggregate fails, because the column is not in GROUP BY).
  • An extra one-to-many join: the sums multiply.
  • Sorting by SUM without DESC: the top turns into the "smallest".

Check yourself

A JOIN cards c ON c.user_id = u.id was added to the query, and Anna has two cards. What happens to Anna's total_deposits?

Answer

Each of her deposits joins with both cards, so there are twice as many rows and the sum becomes 1000 instead of 500. This is a fan-out: after every one-to-many JOIN the row count must be checked. Cards are not needed in this task, so the join should go.

Why does FETCH FIRST 3 ROWS WITH TIES stop working if u.id is added to ORDER BY?

Answer

Equality is judged over all ORDER BY columns. With a unique u.id no two rows are equal, so there are no ties and exactly three rows come back.

In an interview. Junior: I join users, accounts and transactions, filter completed deposits in WHERE, group by user, sort by the sum in descending order and take three. Middle/Senior: I ask what to do with equal sums at the boundary: LIMIT cuts arbitrarily, so I add a second sort key, and if everyone tied must be shown I take RANK or WITH TIES. I watch the row count after every JOIN and the currencies.

More articles in this chapter