Filtering Merchants by Chargeback Rate: Row vs Group Filters
SQL & DataModel answerLast 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
- Write a SQL query that returns every merchant whose chargeback rate over the last 30 days is strictly greater than 0.5%. Use
HAVINGfor the rate condition. - Explain, in your own words:
- why a condition on an aggregate cannot be placed in
WHERE; - what
HAVINGdoes and where it sits relative toGROUP BY; - how SQL dialects differ here (for example, aliases in
HAVING, and MySQL acceptingHAVINGwithoutGROUP BY); - performance considerations when the table is large.
- why a condition on an aggregate cannot be placed in
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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
WHERE filters rows before grouping. HAVING filters groups after aggregation. A chargeback rate describes a merchant's whole set of transactions, not any single row, so the rate condition goes in HAVING, while row-level conditions (status, date range) go in WHERE.
Logical evaluation order
FROM/JOINWHEREGROUP BY- Aggregates (
COUNT,SUM, ...) HAVINGSELECT(expressions, aliases)DISTINCT,ORDER BY,LIMIT
When WHERE runs, no groups exist, so SUM(...) has nothing to operate on. That is why the standard forbids aggregates there. HAVING runs after step 4 and can use both aggregates and grouping columns.
Define the metric first
- Denominator: settled transactions created in the last 30 days (count-based; amount-based is an alternative).
- Numerator: those transactions with at least one chargeback.
- Threshold: 0.5% is
0.005, not0.5. - Maturity caveat: chargebacks arrive weeks after the sale, so a fresh 30-day cohort understates the true rate. A lagged window (e.g. transactions 60 to 30 days old) is a reasonable alternative to mention.
Query
WITH recent_txn AS (
SELECT
t.merchant_id,
t.txn_id,
CASE WHEN EXISTS (
SELECT 1 FROM chargebacks c WHERE c.txn_id = t.txn_id
) THEN 1 ELSE 0 END AS is_cb
FROM transactions t
WHERE t.status = 'SETTLED'
AND t.txn_ts >= CURRENT_TIMESTAMP - INTERVAL '30 days'
)
SELECT
merchant_id,
COUNT(*) AS txn_count,
SUM(is_cb) AS cb_count,
SUM(is_cb) * 1.0 / COUNT(*) AS chargeback_rate
FROM recent_txn
GROUP BY merchant_id
HAVING SUM(is_cb) > 0.005 * COUNT(*)
-- AND COUNT(*) >= 200 -- optional minimum-volume guard
ORDER BY chargeback_rate DESC;
Why it is correct
- Filters split by level. Status and time are row properties (
WHERE); the rate is a group property (HAVING). - No double counting.
EXISTSflags each transaction once even with several chargebacks. A bareLEFT JOINwould duplicate rows and inflate both numerator and denominator. - No integer division. In PostgreSQL and SQL Server,
SUM(x) / COUNT(*)on integers truncates to 0. Multiplying by1.0fixes the displayed rate. - No division in the filter.
SUM(is_cb) > 0.005 * COUNT(*)sidesteps divide-by-zero, a habit that matters for amount-based rates where the denominator can be 0. - Portable HAVING. Repeating the aggregate expressions avoids relying on the
chargeback_ratealias.
Dialect differences
- Aliases in HAVING: MySQL, SQLite, and some warehouses (BigQuery, Snowflake) accept them. PostgreSQL, SQL Server, and Oracle do not.
- HAVING without GROUP BY: In standard SQL the entire result is one group, so
SELECT COUNT(*) FROM t HAVING COUNT(*) > 10returns one row or none. MySQL additionally letsHAVINGreference non-aggregated select-list columns and aliases withoutGROUP BY, acting like a post-SELECTWHERE. This is non-portable; avoid it. - Non-grouped columns: older MySQL modes returned arbitrary values;
ONLY_FULL_GROUP_BY(default in modern versions) rejects this like standard SQL. - Conditional counting: PostgreSQL has
COUNT(*) FILTER (WHERE ...); elsewhere useSUM(CASE WHEN ... THEN 1 ELSE 0 END). - Window functions: not allowed in
WHEREorHAVING. Use a subquery, orQUALIFYwhere supported (Snowflake, BigQuery, Teradata, DuckDB).
Performance
- Filter early. Row predicates in
WHEREshrink the data before aggregation. A row-level predicate inHAVINGis legal but logically post-aggregation; some optimizers push it down, but do not depend on it. - Sargable dates.
txn_ts >= <bound>allows index range scans and partition pruning. Wrapping the column (DATE(txn_ts)) or moving it to the other side of an arithmetic expression can defeat both. - Indexes / layout. OLTP: composite index on
(txn_ts, merchant_id, status)and an index onchargebacks(txn_id)for the semi-join. Warehouse: partition by date, cluster bymerchant_id. - Aggregate before joining to dimension tables such as
merchants, so you do not multiply rows first. - Rollups for monitoring. Maintain a daily
merchant_day(txn_count, cb_count)table and sum the last 30 days instead of rescanning raw data.
Complexity
With N transactions in the window, C chargebacks, M merchants:
- Time: O(N + C) with a hash semi-join and hash aggregation; O(N log N) with sort-based grouping.
- Space: O(M) for the aggregation table, plus O(C) if the semi-join hashes chargeback
txn_ids.
Edge cases
- Low-volume merchants: 1 chargeback in 3 transactions is 33% but mostly noise. Add
COUNT(*) >= k. - Several chargebacks per transaction: handled by
EXISTSorCOUNT(DISTINCT txn_id). - Refunded or voided transactions: decide explicitly whether they stay in the denominator.
- Window boundary and time zones: choose between calendar days (
CURRENT_DATE - 30) and a rolling 720 hours. - Merchants with no transactions: no group exists, so they do not appear.
Validation
- Pick one flagged merchant and recompute its counts by hand from raw rows.
- Check that
cb_count <= txn_countfor every row. - Compare the row count of the CTE with and without the chargebacks join to confirm no duplication.
- Test boundary cases: a merchant exactly at 0.5% must be excluded (strict
>).
pandas equivalent
import pandas as pd
def high_chargeback_merchants(transactions, chargebacks, as_of,
threshold=0.005, min_txns=1):
start = as_of - pd.Timedelta(days=30)
t = transactions[
(transactions["status"] == "SETTLED")
& (transactions["txn_ts"] >= start)
& (transactions["txn_ts"] <= as_of)
].copy()
# EXISTS semantics: one flag per transaction
t["is_cb"] = t["txn_id"].isin(chargebacks["txn_id"]).astype(int)
g = t.groupby("merchant_id").agg(
txn_count=("txn_id", "size"),
cb_count=("is_cb", "sum"),
)
g["chargeback_rate"] = g["cb_count"] / g["txn_count"]
# HAVING: filter after aggregation
out = g[(g["cb_count"] > threshold * g["txn_count"])
& (g["txn_count"] >= min_txns)]
return out.sort_values("chargeback_rate", ascending=False).reset_index()
The boolean filter on t mirrors WHERE; the filter on g mirrors HAVING.