KatInterview

Filtering Merchants by Chargeback Rate: Row vs Group Filters

SQL & DataModel answer
MediumModel answerSQL & Datasqlgroup-byhaving

Last updated

Find merchants whose 30-day chargeback rate exceeds 0.5% and explain why the rate filter belongs after grouping, plus dialect quirks and performance implications.

You work with a payments dataset and need to flag risky merchants.

Schema (assumed)

  • transactions(txn_id, merchant_id, txn_ts, status, amount)
  • chargebacks(chargeback_id, txn_id, created_at)

A transaction may have zero, one, or several chargebacks.

Task

  1. Write a SQL query that returns every merchant whose chargeback rate over the last 30 days is strictly greater than 0.5%. Use HAVING for the rate condition.
  2. Explain, in your own words:
    • why a condition on an aggregate cannot be placed in WHERE;
    • what HAVING does and where it sits relative to GROUP BY;
    • how SQL dialects differ here (for example, aliases in HAVING, and MySQL accepting HAVING without GROUP BY);
    • performance considerations when the table is large.

What to include

  • State how you define the metric (numerator, denominator, time window, which statuses count) before writing the query.
  • Show the output columns you would return (merchant, volume, chargeback count, rate).
  • Point out edge cases such as tiny merchants, multiple chargebacks on one transaction, and integer division.
  • Briefly say how you would sanity-check the result.
  • Optionally, sketch the same logic in pandas.

Hints

Hint 1

Ask yourself which conditions describe a single transaction row (status, timestamp) and which describe a merchant's whole set of transactions (the rate). Each kind belongs in a different clause.

Hint 2

Think about the logical order in which SQL evaluates clauses. At the moment WHERE runs, have any groups or aggregates been computed yet?

Hint 3

A plain LEFT JOIN to chargebacks duplicates transaction rows when there are several chargebacks. Consider an EXISTS check or COUNT(DISTINCT txn_id) so each transaction is counted once.

Hint 4

To avoid integer-division truncation and divide-by-zero, compare SUM(flag) > 0.005 * COUNT(*) in HAVING instead of dividing.