Merchant Chargeback Filtering Using WHERE and HAVING
Medium · Data Manipulation (SQL/Python) · Data Scientist · Onsite
Problem Statement
Payment risk teams monitor merchant dispute activity on transactions by separating row-level date filtering (WHERE) from group-level metric thresholds (HAVING). Assuming a fixed reference date of 2025-09-30, the trailing 30-day evaluation window covers 2025-09-01 through 2025-09-30 inclusive.
Write a SQL query (QUERY in SQLite dialect) using GROUP BY and HAVING that returns every merchant whose 30-day chargeback_rate is strictly above 0.5% (0.005), returning two columns in exact order:
merchant_id— identifier of the flagged merchant.chargeback_rate— proportion of that merchant's transactions inside2025-09-01..2025-09-30whereis_chargebackis true, expressed as a decimal fraction rounded to 4 decimal places.
Treat rows where is_chargeback is NULL as non-chargebacks (0 in the numerator) while still counting them toward the merchant's total transactions in the denominator. Evaluate the > 0.005 cutoff before display rounding, and return rows in any order.
In an interview discussion alongside your query, be ready to explain why WHERE cannot evaluate aggregate expressions, how HAVING operates on grouped buckets after GROUP BY, SQL dialect differences around HAVING without GROUP BY (such as MySQL vs PostgreSQL/SQLite), and why filtering dates in WHERE matters for index and partition efficiency.
Input Schema
transactions
| Column | Type | Description |
|---|---|---|
transaction_id |
VARCHAR |
Unique payment record identifier. |
merchant_id |
VARCHAR |
Merchant account identifier. |
transaction_date |
DATE |
Settlement date (YYYY-MM-DD). |
amount |
DECIMAL(10,2) |
Payment value in dollars. |
is_chargeback |
BOOLEAN |
TRUE if disputed via chargeback, FALSE or NULL otherwise. |
Examples
Example 1
Input:
transactions
transaction_id |
merchant_id |
transaction_date |
amount |
is_chargeback |
|---|---|---|---|---|
'tx_101' |
'shop_a' |
'2025-09-02' |
40.00 |
FALSE |
'tx_102' |
'shop_a' |
'2025-09-07' |
15.00 |
TRUE |
'tx_103' |
'shop_a' |
'2025-09-14' |
25.00 |
NULL |
'tx_104' |
'shop_a' |
'2025-09-23' |
20.00 |
FALSE |
'tx_105' |
'shop_b' |
'2025-09-09' |
120.00 |
FALSE |
'tx_106' |
'shop_b' |
'2025-09-21' |
85.00 |
FALSE |
'tx_107' |
'shop_c' |
'2025-08-24' |
95.00 |
TRUE |
'tx_108' |
'shop_c' |
'2025-09-18' |
45.00 |
FALSE |
'tx_109' |
'shop_d' |
'2025-09-04' |
12.00 |
TRUE |
'tx_110' |
'shop_d' |
'2025-09-16' |
30.00 |
FALSE |
'tx_111' |
'shop_d' |
'2025-09-30' |
18.00 |
TRUE |
Expected Output:
merchant_id |
chargeback_rate |
|---|---|
'shop_a' |
0.25 |
'shop_d' |
0.6667 |
Explanation:
- 'shop_a' has 4 September transactions (tx_103's NULL flag stays in the denominator as a non-chargeback) and 1 chargeback: 1 / 4 = 0.25 > 0.005.
- 'shop_b' has 0 / 2 = 0.0 and is excluded.
- 'shop_c''s August chargeback (tx_107, '2025-08-24') is removed by WHERE before grouping, leaving 0 / 1 = 0.0 in September.
- 'shop_d' has 2 chargebacks out of 3 September transactions (including boundary date '2025-09-30'): 2 / 3 = 0.6667 > 0.005.
Constraints
- Reference date is fixed at
'2025-09-30'; includetransaction_datevalues from'2025-09-01'through'2025-09-30'inclusive and exclude all other dates. - The threshold is strictly greater than
0.5%(> 0.005) evaluated on the unrounded fraction (for example,1 / 200 = 0.005is excluded, whereas1 / 199 = 0.005025...is included and displayed as0.005). is_chargebackmay beTRUE,FALSE, orNULL.- Format
chargeback_rateas a decimal fraction in[0, 1]rounded to 4 decimal places (not a0..100percentage); output row order is unrestricted.
Step-by-step walkthrough
Understand the goal and the two kinds of filters
We are given a single table,
transactions(transaction_id, merchant_id, transaction_date, amount, is_chargeback), and asked to returnmerchant_id, chargeback_ratefor every merchant whose chargeback rate in the last 30 days is strictly above0.5%.Let's pin down every exact rule:
- "Last 30 days": With "today" fixed at
2025-09-30, the window covers2025-09-01through2025-09-30inclusive. - Rate scale and rounding:
0.5%as a decimal fraction is0.005. Returnchargeback_rateas a fraction rounded to 4 decimals (for example,1 / 3 -> 0.3333, not33.33), keeping only merchants with rate strictly greater than0.005. NULLhandling: Ifis_chargebackisNULL, that row is not a chargeback (0in the numerator), yet it is still a real transaction (+1in the denominator).
Notice that our problem contains two completely different kinds of filters:
- "In the last 30 days" is a test on each individual transaction row.
- "Chargeback rate > 0.5%" is a test on each merchant's aggregated group of rows.
That distinction is the exact reason SQL has both
WHEREandHAVING.- "Last 30 days": With "today" fixed at
Understand SQL's logical execution order: WHERE vs HAVING
Even though
SELECTis written first in a SQL query, every SQL engine logically evaluates clauses in a strict pipeline:Raw rows Keep valid Collapse rows Keep valid Compute & from table single rows into buckets buckets format output +------------+ +-----------+ +--------------+ +------------+ +------------+ | FROM |-->| WHERE |-->| GROUP BY |-->| HAVING |-->| SELECT | | transactions | row check | | merchant_id | | group check| | ROUND(...) | +------------+ +-----------+ +--------------+ +------------+ +------------+- Why
WHEREcannot use aggregates: WhenWHEREruns, the engine is inspecting one raw transaction row at a time. Merchant buckets do not exist yet, so asking forSUM(...)orCOUNT(*)insideWHEREhas nothing to sum over—databases immediately reject it (misuse of aggregatein SQLite;aggregate functions are not allowed in WHEREin PostgreSQL). - How
HAVINGworks afterGROUP BY:GROUP BY merchant_idcollapses all surviving September rows into one bucket per merchant.HAVINGruns right afterGROUP BY, inspecting one whole merchant bucket at a time, so it can computeSUM(...)andCOUNT(*)across that merchant's rows.
- Why
Filter individual rows first with WHERE
To keep transactions from
2025-09-01through2025-09-30inclusive, write a half-open date range—inclusive at the start (>= '2025-09-01') and strictly exclusive at the day after the end (< '2025-10-01'):- On pure
DATEvalues ('YYYY-MM-DD'), this matches2025-09-01through2025-09-30identically toBETWEEN '2025-09-01' AND '2025-09-30'. - Unlike
BETWEEN, the half-open form also stays bug-free iftransaction_dateever stores timestamps like'2025-09-30 14:30:00'(where<= '2025-09-30'would silently drop afternoon transactions on September 30). - Placing this filter in
WHEREis essential for correctness (excluding August chargebacks likeshop_c'stx_107before grouping) and performance (letting the database use an index or date partitions ontransaction_dateso old months never enter theGROUP BYhash table).
FROM transactions -- WHERE runs before GROUP BY: filter individual rows to the 30-day window [2025-09-01, 2025-10-01) WHERE transaction_date >= '2025-09-01' AND transaction_date < '2025-10-01' GROUP BY merchant_id- On pure
Aggregate per merchant and handle NULL flags safely
Inside each
merchant_idgroup, we computechargeback_rateusing conditional aggregation—summing aCASE WHEN ... THEN 1 ELSE 0 ENDexpression across the group:- Numerator (
SUM(CASE WHEN is_chargeback THEN 1 ELSE 0 END)): Adds1whenis_chargebackis true, and0when it is false orNULL. - Denominator (
COUNT(*)): Counts every September transaction row in the group, including rows whereis_chargebackisNULL. (Do not useAVG(is_chargeback)orCOUNT(is_chargeback): SQL aggregates ignoreNULLvalues, which would shrink the denominator from 4 rows to 2 if two flags wereNULL!) - Float division (
1.0 *): In SQLite and PostgreSQL, dividing two integers (1 / 3) truncates to0. Multiplying by1.0forces decimal division, andROUND(..., 4)formats the output column to 4 decimal places. (Note thatCOUNT(*)is guaranteed>= 1for every group that reachesGROUP BY.)
SELECT merchant_id, -- Conditional sum over COUNT(*) treats NULL flags as non-chargebacks while keeping them in the denominator ROUND( 1.0 * SUM(CASE WHEN is_chargeback THEN 1 ELSE 0 END) / COUNT(*), 4 ) AS chargeback_rate- Numerator (
Filter merchant groups with HAVING and watch dialect rules
Now apply the
> 0.5%(> 0.005) threshold inHAVING:-- HAVING runs after GROUP BY: filter whole merchant groups using the unrounded > 0.5% (0.005) threshold HAVING 1.0 * SUM(CASE WHEN is_chargeback THEN 1 ELSE 0 END) / COUNT(*) > 0.005Why repeat the formula instead of writing
HAVING chargeback_rate > 0.005?- Standard SQL portability: Look back at the execution pipeline—
HAVINGruns beforeSELECT, so in ANSI SQL (and PostgreSQL, SQL Server, Oracle, Snowflake) the aliaschargeback_ratedoes not exist yet whenHAVINGexecutes! - Rounding accuracy:
chargeback_rateinSELECTis rounded to 4 decimals. If a merchant has1chargeback in199transactions, their true rate is0.005025... > 0.005(so they must be flagged), yetROUND(..., 4)turns it into0.005, which would falsely fail> 0.005!
Key SQL dialect differences interviewers test on
HAVING:- Aliases in
HAVING: Allowed in MySQL, SQLite, and BigQuery as a non-standard convenience; rejected in PostgreSQL and SQL Server. HAVINGwithoutGROUP BY(with aggregates): Valid ANSI SQL—treats the entire filtered table as one single group (for example,SELECT COUNT(*) FROM transactions HAVING COUNT(*) > 100), supported by PostgreSQL and SQLite.HAVINGwithoutGROUP BYand without aggregates: MySQL uniquely permits queries likeSELECT transaction_id, amount * 100 AS cents FROM transactions HAVING cents > 5000, treatingHAVINGlike a lateWHEREthat can readSELECTaliases. SQLite rejects this (HAVING clause on a non-aggregate query), and PostgreSQL rejects it becauseHAVINGforces single-group aggregation.
- Standard SQL portability: Look back at the execution pipeline—
Trace Example 1 step by step
First,
WHEREcheckstransaction_dateon all 11 sample rows and dropstx_107(shop_c,'2025-08-24', chargeback):Step 1 (WHERE [2025-09-01, 2025-10-01)): Dropped: tx_107 (shop_c, 2025-08-24, True) <-- outside the 30-day window! Kept: tx_101..tx_104 (shop_a); tx_105, tx_106 (shop_b); tx_108 (shop_c); tx_109..tx_111 (shop_d) Step 2 & 3 (GROUP BY merchant_id -> HAVING unrounded_rate > 0.005): merchant | Sept rows | chargebacks | unrounded rate | > 0.005? | output ROUND(..., 4) ---------+------------------------+-------------------+----------------+----------+--------------------- shop_a | tx_101..tx_104 (1 NULL)| 1 (tx_102) | 1/4 = 0.25 | YES | 0.25 shop_b | tx_105, tx_106 | 0 | 0/2 = 0.0 | no | (filtered out) shop_c | tx_108 | 0 | 0/1 = 0.0 | no | (filtered out) shop_d | tx_109..tx_111 | 2 (tx_109, tx_111)| 2/3 = 0.6666.. | YES | 0.6667Notice how
shop_cwould have shown1 / 2 = 0.5if we had forgotten theWHEREdate filter, andshop_awould have shown1 / 3 = 0.3333if we had ignoredtx_103'sNULLflag! With both clauses in their proper places, the query returns('shop_a', 0.25)and('shop_d', 0.6667).Complete SQL query
Putting every clause together gives the complete solution:
SELECT merchant_id, -- Conditional sum over COUNT(*) treats NULL flags as non-chargebacks while keeping them in the denominator ROUND( 1.0 * SUM(CASE WHEN is_chargeback THEN 1 ELSE 0 END) / COUNT(*), 4 ) AS chargeback_rate FROM transactions -- WHERE runs before GROUP BY: filter individual rows to the 30-day window [2025-09-01, 2025-10-01) WHERE transaction_date >= '2025-09-01' AND transaction_date < '2025-10-01' GROUP BY merchant_id -- HAVING runs after GROUP BY: filter whole merchant groups using the unrounded > 0.5% (0.005) threshold HAVING 1.0 * SUM(CASE WHEN is_chargeback THEN 1 ELSE 0 END) / COUNT(*) > 0.005✅ Submit now — all tests should pass.
Intuition & how it works
Imagine auditing a year of paper payment receipts to flag merchants whose September chargeback rate exceeded 0.5%. You set up two checkpoints separated by a sorting table:
- Checkpoint 1 (
WHERE) stands before the sorting table and inspects one receipt at a time, tossing any non-September receipt straight into the recycling bin. - Next,
GROUP BY merchant_idstacks the surviving September receipts into one pile per merchant and tallies each pile. - Checkpoint 2 (
HAVING) stands after the sorting table, checks each merchant's finished tally (chargebacks / total_receipts > 0.005), and forwards only the high-risk merchants to the final report.
Why do naive approaches fail? Writing WHERE SUM(...) / COUNT(*) > 0.005 fails with a syntax/semantic error in every SQL engine because WHERE runs row by row before merchant groups exist. Skipping WHERE (or trying to filter transaction_date inside HAVING) either pollutes September's numbers with old August chargebacks or—in lenient engines like SQLite and old MySQL—checks the date of one arbitrary row per merchant and drops whole merchants at random! Finally, computing the rate with AVG(is_chargeback) instead of COUNT(*) silently ignores NULL flags and inflates the rate.
Walk through Example 1's four merchants (shop_a, shop_b, shop_c, shop_d):
1. WHERE [2025-09-01, 2025-10-01) filters individual rows first:
- shop_c's August chargeback tx_107 ('2025-08-24', True) is discarded immediately.
- 10 September rows survive across shop_a (4 rows, including 1 NULL), shop_b (2 rows), shop_c (1 row), shop_d (3 rows).
2. GROUP BY merchant_id aggregates each merchant's September pile:
- shop_a: 1 chargeback / 4 rows = 0.25
- shop_b: 0 chargebacks / 2 rows = 0.0
- shop_c: 0 chargebacks / 1 row = 0.0
- shop_d: 2 chargebacks / 3 rows = 0.666666...
3. HAVING rate > 0.005 filters groups, then SELECT rounds to 4 decimals:
- Kept: ('shop_a', 0.25) and ('shop_d', 0.6667)
Key SQL concepts used here:
- Logical query processing order: The conceptual sequence (
FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT) that defines what data and aliases exist at each clause. - Conditional aggregation: Wrapping
CASE WHEN condition THEN 1 ELSE 0 ENDinsideSUM(...)to count matching rows inside each group while keeping non-matching rows forCOUNT(*). - Half-open interval
[start, end_exclusive): Filtering>= '2025-09-01' AND < '2025-10-01'so every moment of September 30 is included even if timestamps are present. - Covering index: A multi-column database index that contains every column a query reads, allowing the engine to answer the query from the index alone without fetching full table rows.
- Partition pruning: When a data warehouse stores table files split by date (such as daily or monthly folders) and skips reading irrelevant folders entirely thanks to a
WHEREfilter ontransaction_date.
Complexity
Let N be total rows in transactions, W be rows inside the 30-day September window (W <= N), and M be distinct merchants active during that window (M <= W).
- Time: Without an index,
WHEREscans all N rows in O(N) time; with an index or date partitioning ontransaction_date, it seeks to'2025-09-01'and scans only the W matching rows in O(log N + W) time. Grouping those W rows bymerchant_idtakes O(W) average time with a hash aggregate (or O(W log W) with sort aggregation), andHAVING+SELECTevaluate one formula per merchant in O(M) time. - Space: O(M) memory to maintain two running integers (chargeback count and row count) per active merchant during aggregation.
Performance & indexes: Filtering in WHERE before GROUP BY is critical for speed: if transactions holds 3 years of history (N = 1,000,000,000) and 30 days is W = 27,000,000, WHERE eliminates 97% of the rows before hashing or sorting ever begins. Even for conditions on grouping columns (such as merchant_id <> 'test_acct'), always write row filters in WHERE rather than relying on the query optimizer to push them down from HAVING. A composite covering index on (transaction_date, merchant_id, is_chargeback) lets the engine range-scan the 30-day slice and aggregate directly from the index pages.
Edge cases
- Exact window boundaries:
'2025-09-01'and'2025-09-30'are included;'2025-08-31'and'2025-10-01'are excluded. - Rate exactly equal to
0.5%(0.005): Excluded because the problem specifies strictly> 0.005(for example,1chargeback out of200transactions gives0.005and is not returned). - Unrounded vs rounded boundary (
1 / 199):1 / 199 = 0.005025...is strictly above0.005, so ourHAVINGexpression keeps the merchant andSELECTdisplays0.005. Filtering on the rounded alias would wrongly drop this merchant! NULLinis_chargeback:CASE WHEN is_chargeback THEN 1 ELSE 0 ENDevaluatesNULLto0, whileCOUNT(*)keeps the row in the denominator ([True, None, None, False]gives1 / 4 = 0.25).- Merchants with only pre-September activity: Eliminated by
WHEREbeforeGROUP BY, so they have zero September transactions and do not appear. - Empty table (or zero rows in window): Produces zero groups and returns an empty result set cleanly.
Common mistakes
- Putting
SUMorCOUNTinWHERE: Fails to parse/compile in every SQL dialect becauseWHEREexecutes beforeGROUP BY. - Putting
transaction_dateinHAVING(or omittingWHERE): Standard SQL (PostgreSQL, SQL Server) rejectsHAVING transaction_date >= ...becausetransaction_dateis not grouped; SQLite and MySQL (withONLY_FULL_GROUP_BYdisabled) silently inspect one arbitrary row's date per merchant, corrupting results! - Referencing the
SELECTaliaschargeback_rateinHAVING: Works in SQLite and MySQL, but fails withcolumn "chargeback_rate" does not existin PostgreSQL and SQL Server—and introduces a rounding bug at1 / 199. - Using
AVG(is_chargeback)orCOUNT(is_chargeback): Skips rows whereis_chargeback IS NULL, shrinking the denominator and over-reporting the chargeback rate. - Writing
> 0.5instead of> 0.005:0.5%means0.5 / 100 = 0.005;> 0.5checks for a50%chargeback rate! - Integer division (
SUM(...) / COUNT(*)without1.0 *): Truncates every rate below100%down to0in SQLite and PostgreSQL.
Alternative approaches
- CTE to avoid repeating the aggregate expression: If you dislike writing the
SUM(...) / COUNT(*)expression twice (once inSELECTand once inHAVING), compute the unrounded counts or rate in a CTE usingGROUP BY, then filter withWHEREin the outer query! Remember to keep the unrounded rate for filtering and round only in the outerSELECT:
sql
WITH merchant_stats AS (
SELECT
merchant_id,
1.0 * SUM(CASE WHEN is_chargeback THEN 1 ELSE 0 END) / COUNT(*) AS raw_rate
FROM transactions
WHERE transaction_date >= '2025-09-01'
AND transaction_date < '2025-10-01'
GROUP BY merchant_id
)
SELECT merchant_id, ROUND(raw_rate, 4) AS chargeback_rate
FROM merchant_stats
WHERE raw_rate > 0.005
- Exact integer cross-multiplication in
HAVING: BecauseCOUNT(*) > 0and0.005 = 1 / 200,cb / total > 1 / 200is algebraically identical to200 * SUM(CASE WHEN is_chargeback THEN 1 ELSE 0 END) > COUNT(*), avoiding floating-point division in the filter completely.
Follow-up questions
-
How do you stop a newly onboarded merchant with one dispute on two orders from triggering noisy chargeback alerts? Pair the rate threshold with a minimum sample-size guardrail directly inside
HAVING, such asAND COUNT(*) >= 50(or require the lower bound of a Wilson score confidence interval to exceed0.005so small-denominator noise cannot trigger an alert). Because order volume is itself a group-level aggregate,HAVINGis the natural clause to enforce both conditions together. -
How should you parameterize the 30-day window for a scheduled daily pipeline, and why do recent purchase dates understate true chargeback risk? Replace hardcoded September literals with an explicit
:as_of_dateparameter so historical backfills stay deterministic—for instance,transaction_date >= date(:as_of_date, '-29 days') AND transaction_date < date(:as_of_date, '+1 day')in SQLite (or:as_of_date - INTERVAL '29 days'and:as_of_date + INTERVAL '1 day'in PostgreSQL). In payments, cardholders typically file disputes 15–60 days after the settlement date, so transactions from the past week look artificially clean; risk teams therefore combine matured purchase cohorts (45–60 days old) with early-warning alerts keyed onchargeback_received_date. -
How would you switch from a transaction-count rate to a dollar-weighted chargeback rate, and when is each metric preferred? Weight both the numerator and denominator by
amount:1.0 * SUM(CASE WHEN is_chargeback THEN amount ELSE 0 END) / NULLIF(SUM(amount), 0)(usingNULLIFin case total volume is$0). Card networks enforce count-based thresholds to catch high-velocity card-testing fraud on tiny$1charges, whereas payment processors also track dollar-weighted rates to measure true financial exposure (in Example 1,shop_a's count rate is1 / 4 = 0.2500, while its dollar rate is$15 / $100 = 0.1500).
Follow-up questions
- How do you stop a newly onboarded merchant with one dispute on two orders from triggering noisy chargeback alerts?
- How should you parameterize the 30-day window for a scheduled daily pipeline, and why do recent purchase dates understate true chargeback risk?
- How would you switch from a transaction-count rate to a dollar-weighted chargeback rate, and when is each metric preferred?
Similar questions
- Monthly Activity Filtering and Purchase Interval Summary
- Merchant GMV Aggregation with SQL Windows, Joins, and Python
- Peak Session Overlap Count
- Users Matching Daily Page Transition Rule
- Merchant Transaction Summaries via Conditional Aggregation
- Conditional Aggregation with CASE and HAVING
More PayPal interview questions
- Evaluating Online Payments and Cold-Start Fraud Controls Hard
- Two-Die Wager Expected Value Easy
- Four-Stop Building Elevator Dispatch Policy Medium Pro
- Comparing Python Lists and Tuples Hard Pro
- Risk Experience and Strategy-Focused Role Alignment Medium Pro
- Unsupervised Fraud Detection and Label-Scarce Evaluation Hard Pro
- Hypothesis Testing and p-Value Pitfalls in Fraud Experiments Hard Pro
- Curbing Airport Pickup Cancellations Under Queue Interference Easy Pro
- Expected Value of a Dice Wager Easy Pro
- Merchant Transaction Summaries via Conditional Aggregation Medium Pro