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:

  1. merchant_id — identifier of the flagged merchant.
  2. chargeback_rate — proportion of that merchant's transactions inside 2025-09-01..2025-09-30 where is_chargeback is 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'; include transaction_date values 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.005 is excluded, whereas 1 / 199 = 0.005025... is included and displayed as 0.005).
  • is_chargeback may be TRUE, FALSE, or NULL.
  • Format chargeback_rate as a decimal fraction in [0, 1] rounded to 4 decimal places (not a 0..100 percentage); output row order is unrestricted.

Step-by-step walkthrough

  1. 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 return merchant_id, chargeback_rate for every merchant whose chargeback rate in the last 30 days is strictly above 0.5%.

    Let's pin down every exact rule:

    • "Last 30 days": With "today" fixed at 2025-09-30, the window covers 2025-09-01 through 2025-09-30 inclusive.
    • Rate scale and rounding: 0.5% as a decimal fraction is 0.005. Return chargeback_rate as a fraction rounded to 4 decimals (for example, 1 / 3 -> 0.3333, not 33.33), keeping only merchants with rate strictly greater than 0.005.
    • NULL handling: If is_chargeback is NULL, that row is not a chargeback (0 in the numerator), yet it is still a real transaction (+1 in the denominator).

    Notice that our problem contains two completely different kinds of filters:

    1. "In the last 30 days" is a test on each individual transaction row.
    2. "Chargeback rate > 0.5%" is a test on each merchant's aggregated group of rows.

    That distinction is the exact reason SQL has both WHERE and HAVING.

  2. Understand SQL's logical execution order: WHERE vs HAVING

    Even though SELECT is 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 WHERE cannot use aggregates: When WHERE runs, the engine is inspecting one raw transaction row at a time. Merchant buckets do not exist yet, so asking for SUM(...) or COUNT(*) inside WHERE has nothing to sum over—databases immediately reject it (misuse of aggregate in SQLite; aggregate functions are not allowed in WHERE in PostgreSQL).
    • How HAVING works after GROUP BY: GROUP BY merchant_id collapses all surviving September rows into one bucket per merchant. HAVING runs right after GROUP BY, inspecting one whole merchant bucket at a time, so it can compute SUM(...) and COUNT(*) across that merchant's rows.
  3. Filter individual rows first with WHERE

    To keep transactions from 2025-09-01 through 2025-09-30 inclusive, 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 DATE values ('YYYY-MM-DD'), this matches 2025-09-01 through 2025-09-30 identically to BETWEEN '2025-09-01' AND '2025-09-30'.
    • Unlike BETWEEN, the half-open form also stays bug-free if transaction_date ever 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 WHERE is essential for correctness (excluding August chargebacks like shop_c's tx_107 before grouping) and performance (letting the database use an index or date partitions on transaction_date so old months never enter the GROUP BY hash 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
    
  4. Aggregate per merchant and handle NULL flags safely

    Inside each merchant_id group, we compute chargeback_rate using conditional aggregation—summing a CASE WHEN ... THEN 1 ELSE 0 END expression across the group:

    • Numerator (SUM(CASE WHEN is_chargeback THEN 1 ELSE 0 END)): Adds 1 when is_chargeback is true, and 0 when it is false or NULL.
    • Denominator (COUNT(*)): Counts every September transaction row in the group, including rows where is_chargeback is NULL. (Do not use AVG(is_chargeback) or COUNT(is_chargeback): SQL aggregates ignore NULL values, which would shrink the denominator from 4 rows to 2 if two flags were NULL!)
    • Float division (1.0 *): In SQLite and PostgreSQL, dividing two integers (1 / 3) truncates to 0. Multiplying by 1.0 forces decimal division, and ROUND(..., 4) formats the output column to 4 decimal places. (Note that COUNT(*) is guaranteed >= 1 for every group that reaches GROUP 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
    
  5. Filter merchant groups with HAVING and watch dialect rules

    Now apply the > 0.5% (> 0.005) threshold in HAVING:

    -- 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
    

    Why repeat the formula instead of writing HAVING chargeback_rate > 0.005?

    1. Standard SQL portability: Look back at the execution pipeline—HAVING runs before SELECT, so in ANSI SQL (and PostgreSQL, SQL Server, Oracle, Snowflake) the alias chargeback_rate does not exist yet when HAVING executes!
    2. Rounding accuracy: chargeback_rate in SELECT is rounded to 4 decimals. If a merchant has 1 chargeback in 199 transactions, their true rate is 0.005025... > 0.005 (so they must be flagged), yet ROUND(..., 4) turns it into 0.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.
    • HAVING without GROUP 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.
    • HAVING without GROUP BY and without aggregates: MySQL uniquely permits queries like SELECT transaction_id, amount * 100 AS cents FROM transactions HAVING cents > 5000, treating HAVING like a late WHERE that can read SELECT aliases. SQLite rejects this (HAVING clause on a non-aggregate query), and PostgreSQL rejects it because HAVING forces single-group aggregation.
  6. Trace Example 1 step by step

    First, WHERE checks transaction_date on all 11 sample rows and drops tx_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.6667
    

    Notice how shop_c would have shown 1 / 2 = 0.5 if we had forgotten the WHERE date filter, and shop_a would have shown 1 / 3 = 0.3333 if we had ignored tx_103's NULL flag! With both clauses in their proper places, the query returns ('shop_a', 0.25) and ('shop_d', 0.6667).

  7. 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:

  1. 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.
  2. Next, GROUP BY merchant_id stacks the surviving September receipts into one pile per merchant and tallies each pile.
  3. 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 END inside SUM(...) to count matching rows inside each group while keeping non-matching rows for COUNT(*).
  • 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 WHERE filter on transaction_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, WHERE scans all N rows in O(N) time; with an index or date partitioning on transaction_date, it seeks to '2025-09-01' and scans only the W matching rows in O(log N + W) time. Grouping those W rows by merchant_id takes O(W) average time with a hash aggregate (or O(W log W) with sort aggregation), and HAVING + SELECT evaluate 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, 1 chargeback out of 200 transactions gives 0.005 and is not returned).
  • Unrounded vs rounded boundary (1 / 199): 1 / 199 = 0.005025... is strictly above 0.005, so our HAVING expression keeps the merchant and SELECT displays 0.005. Filtering on the rounded alias would wrongly drop this merchant!
  • NULL in is_chargeback: CASE WHEN is_chargeback THEN 1 ELSE 0 END evaluates NULL to 0, while COUNT(*) keeps the row in the denominator ([True, None, None, False] gives 1 / 4 = 0.25).
  • Merchants with only pre-September activity: Eliminated by WHERE before GROUP 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 SUM or COUNT in WHERE: Fails to parse/compile in every SQL dialect because WHERE executes before GROUP BY.
  • Putting transaction_date in HAVING (or omitting WHERE): Standard SQL (PostgreSQL, SQL Server) rejects HAVING transaction_date >= ... because transaction_date is not grouped; SQLite and MySQL (with ONLY_FULL_GROUP_BY disabled) silently inspect one arbitrary row's date per merchant, corrupting results!
  • Referencing the SELECT alias chargeback_rate in HAVING: Works in SQLite and MySQL, but fails with column "chargeback_rate" does not exist in PostgreSQL and SQL Server—and introduces a rounding bug at 1 / 199.
  • Using AVG(is_chargeback) or COUNT(is_chargeback): Skips rows where is_chargeback IS NULL, shrinking the denominator and over-reporting the chargeback rate.
  • Writing > 0.5 instead of > 0.005: 0.5% means 0.5 / 100 = 0.005; > 0.5 checks for a 50% chargeback rate!
  • Integer division (SUM(...) / COUNT(*) without 1.0 *): Truncates every rate below 100% down to 0 in SQLite and PostgreSQL.

Alternative approaches

  1. CTE to avoid repeating the aggregate expression: If you dislike writing the SUM(...) / COUNT(*) expression twice (once in SELECT and once in HAVING), compute the unrounded counts or rate in a CTE using GROUP BY, then filter with WHERE in the outer query! Remember to keep the unrounded rate for filtering and round only in the outer SELECT:

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

  1. Exact integer cross-multiplication in HAVING: Because COUNT(*) > 0 and 0.005 = 1 / 200, cb / total > 1 / 200 is algebraically identical to 200 * 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 as AND COUNT(*) >= 50 (or require the lower bound of a Wilson score confidence interval to exceed 0.005 so small-denominator noise cannot trigger an alert). Because order volume is itself a group-level aggregate, HAVING is 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_date parameter 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 on chargeback_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) (using NULLIF in case total volume is $0). Card networks enforce count-based thresholds to catch high-velocity card-testing fraud on tiny $1 charges, whereas payment processors also track dollar-weighted rates to measure true financial exposure (in Example 1, shop_a's count rate is 1 / 4 = 0.2500, while its dollar rate is $15 / $100 = 0.1500).

Follow-up questions

Similar questions

More PayPal interview questions

All 53 PayPal questions →