Enrich Card Transactions with Merchant Loyalty Points

Medium · Data Manipulation (SQL/Python) · Software Engineer · Technical Screen

Problem Statement

A loyalty platform receives partner store metadata as a flat file merchants.csv containing three string fields (merchant_name, merchant_code, category) alongside a relational table transactions(user_id INT, merchant_name TEXT, amount DECIMAL(10, 2), transacted_at TIMESTAMP).

Address the workflow below, and implement the core enrichment rule in Python for automated evaluation:

  1. Staging load: Show how to bulk-import merchants.csv into a SQL staging table merchants(merchant_name TEXT, merchant_code TEXT, category TEXT).
  2. Transaction enrichment & point calculation: Produce one output record per transaction containing user_id, merchant_code, category, base_points, and final_points (both point fields as integers):
    • Match merchant_name character-for-character (preserving letter case and spaces). If the same merchant_name appears multiple times in merchants, use its first entry so a single transaction never fans out into multiple output rows.
    • Whenever a transaction's merchant_name is absent from merchants, retain the transaction and fill both merchant_code and category with 'UNKNOWN'.
    • Compute base_points as the mathematical floor of amount (the greatest integer less than or equal to amount, rounding toward negative infinity on negative refunds).
    • Compute final_points after flooring: award 3 * base_points when category equals 'Restaurant', and 1 * base_points for every other category (including 'UNKNOWN').
  3. SQL vs. application layer: Discuss when executing this lookup and conditional multiplier directly inside SQL (LEFT JOIN + CASE) is preferable to fetching raw tables and transforming rows in application memory.
  4. Data hygiene & fuzzy descriptors: Recommend indexes, staging cleanup steps, and practical strategies for reconciling inconsistent merchant_name descriptors.

For the automated judge, implement:

def join_transactions_with_merchant_points(
    transactions: List[List], merchants: List[List]
) -> List[Dict]:

where each item in transactions is [user_id, merchant_name, amount, transacted_at], each item in merchants is [merchant_name, merchant_code, category], and the returned list contains one dictionary per transaction with keys "user_id", "merchant_code", "category", "base_points", and "final_points".

Examples

Example 1

Input:
  transactions = [
    [101, "Ramen House", 18.60, "2025-05-10T12:30:00"],
    [204, "Fresh Market", 53.95, "2025-05-10T15:10:00"],
    [101, "Pop-Up Bakery", 7.40, "2025-05-11T08:45:00"]
  ]
  merchants = [
    ["Ramen House", "MRC-10", "Restaurant"],
    ["Fresh Market", "MRC-20", "Grocery"]
  ]

Output:
  [
    {"user_id": 101, "merchant_code": "MRC-10", "category": "Restaurant", "base_points": 18, "final_points": 54},
    {"user_id": 204, "merchant_code": "MRC-20", "category": "Grocery", "base_points": 53, "final_points": 53},
    {"user_id": 101, "merchant_code": "UNKNOWN", "category": "UNKNOWN", "base_points": 7, "final_points": 7}
  ]

"Ramen House" matches a 'Restaurant' partner, so 18.60 floors to 18 and triples to 54. "Fresh Market" is 'Grocery', earning 1x its floored value 53. "Pop-Up Bakery" has no entry in merchants, so it receives 'UNKNOWN' placeholders and 7 points.

Example 2

Input:
  transactions = [
    [12, "Bistro Verde", 0.85, "2025-06-01T11:00:00"],
    [12, "Bistro Verde", 40, "2025-06-01T19:20:00"]
  ]
  merchants = [
    ["Bistro Verde", "MRC-35", "Restaurant"]
  ]

Output:
  [
    {"user_id": 12, "merchant_code": "MRC-35", "category": "Restaurant", "base_points": 0, "final_points": 0},
    {"user_id": 12, "merchant_code": "MRC-35", "category": "Restaurant", "base_points": 40, "final_points": 120}
  ]

Sub-dollar spend 0.85 floors to 0 (0 * 3 = 0), whereas the exact integer spend 40 floors to 40 and triples to 120.

Example 3

Input:
  transactions = [
    [8, "Book Nook", -4.20, "2025-07-15T09:15:00"],
    [9, "Unlisted Kiosk", -0.25, "2025-07-15T10:00:00"]
  ]
  merchants = [
    ["Book Nook", "MRC-50", "Bookstore"]
  ]

Output:
  [
    {"user_id": 8, "merchant_code": "MRC-50", "category": "Bookstore", "base_points": -5, "final_points": -5},
    {"user_id": 9, "merchant_code": "UNKNOWN", "category": "UNKNOWN", "base_points": -1, "final_points": -1}
  ]

Flooring rounds negative refund amounts down toward negative infinity (-4.20 becomes -5, and -0.25 becomes -1), rather than truncating toward zero.

Constraints

  • 0 <= len(transactions) <= 10^5
  • 0 <= len(merchants) <= 10^5
  • user_id is an integer; merchant_name, merchant_code, category, and transacted_at are strings.
  • amount is an int or float (positive, zero, or negative for refunds/adjustments).
  • base_points and final_points in every output dictionary must have Python type int.
  • Output row order may follow input transaction order (SQL evaluation ignores row ordering).

Step-by-step walkthrough

  1. Understand the datasets and the four workflow parts

    We have two inputs:

    1. merchants(merchant_name, merchant_code, category) arriving as an external CSV file merchants.csv.
    2. transactions(user_id, merchant_name, amount, transacted_at) stored in a relational table.
    transactions                                    merchants
    +---------+---------------+--------+            +--------------+---------------+------------+
    | user_id | merchant_name | amount |            | merchant_name| merchant_code | category   |
    +---------+---------------+--------+            +--------------+---------------+------------+
    | 101     | Ramen House   |  18.60 | ---------> | Ramen House  | MRC-10        | Restaurant |
    | 204     | Fresh Market  |  53.95 | ---------> | Fresh Market | MRC-20        | Grocery    |
    | 101     | Pop-Up Bakery |   7.40 | --(miss)-> fallback to ('UNKNOWN', 'UNKNOWN')          |
    +---------+---------------+--------+            +--------------+---------------+------------+
    

    For every transaction row, we must emit user_id, merchant_code, category, base_points, and final_points: - base_points = FLOOR(amount) as an integer. Floor always rounds down toward negative infinity (18.60 -> 18, 0.85 -> 0, and -4.20 -> -5 on refunds). - final_points = 3 * base_points when category is 'Restaurant', and 1 * base_points for every other category (including unmatched merchants). - If merchant_name has no exact match in merchants (case and spaces included), keep the transaction and set both merchant_code and category to 'UNKNOWN'.

    The prompt covers the end-to-end data-engineering workflow (staging ingestion, SQL LEFT JOIN + CASE query, SQL vs. application trade-offs, and indexing/cleaning/fuzzy matching), while the automated judge tests the exact join-and-points rule via join_transactions_with_merchant_points(transactions, merchants) in Python. Let's tackle each part systematically.

  2. Load the CSV into a SQL staging table

    A staging table is a temporary landing table with permissive TEXT columns where raw external files are loaded as-is before cleaning or enforcing strict constraints. Landing data in staging first prevents a single malformed row from aborting an entire ingestion run and lets you inspect and clean anomalies using SQL.

    In PostgreSQL, create the staging table and stream the file with a native bulk CSV loader:

    -- Landing table with plain TEXT columns so raw CSV rows load cleanly.
    CREATE TABLE merchants (
        merchant_name TEXT,
        merchant_code TEXT,
        category      TEXT
    );
    
    -- Bulk-load merchants.csv from the client, skipping the header line.
    \copy merchants FROM 'merchants.csv' WITH (FORMAT csv, HEADER true)
    

    Other SQL engines provide equivalent bulk loaders (LOAD DATA INFILE in MySQL, .import --csv in SQLite, COPY INTO in Snowflake). Prefer a native CSV bulk loader over building row-by-row INSERT strings in a script: it streams data orders of magnitude faster, handles commas inside quoted names like "Noodles, Broth & Tea", and safely parses apostrophes like Luigi's Trattoria without risking broken SQL quotes.

  3. Write the SQL transformation with LEFT JOIN and CASE

    Why must we use LEFT JOIN instead of INNER JOIN? An INNER JOIN keeps only rows that match on both sides, which would silently drop transactions at unlisted stores like Pop-Up Bakery or Sidewalk Florist. A LEFT JOIN preserves every row from the left table (transactions) and fills the right table's (merchants) columns with NULL whenever no match exists.

    -- Deduplicate merchants by merchant_name first so a repeated CSV entry
    -- never fans out one transaction into multiple output rows.
    WITH unique_merchants AS (
        SELECT merchant_name,
               MIN(merchant_code) AS merchant_code,
               MIN(category)      AS category
        FROM merchants
        GROUP BY merchant_name
    )
    SELECT t.user_id,
           -- On an unmatched LEFT JOIN row, m.merchant_name is NULL -> emit 'UNKNOWN'.
           CASE WHEN m.merchant_name IS NULL THEN 'UNKNOWN' ELSE m.merchant_code END AS merchant_code,
           CASE WHEN m.merchant_name IS NULL THEN 'UNKNOWN' ELSE m.category END      AS category,
           -- FLOOR rounds toward -infinity; CAST converts DECIMAL/NUMERIC to INTEGER.
           CAST(FLOOR(t.amount) AS INTEGER)                                          AS base_points,
           -- Multiply AFTER flooring; NULL category falls into ELSE 1 automatically.
           CAST(FLOOR(t.amount) AS INTEGER)
               * CASE WHEN m.category = 'Restaurant' THEN 3 ELSE 1 END               AS final_points
    FROM transactions AS t
    LEFT JOIN unique_merchants AS m
           ON m.merchant_name = t.merchant_name;
    

    Notice three subtle details in that query: - Testing m.merchant_name IS NULL: When a LEFT JOIN finds no match, the join key m.merchant_name is guaranteed to be NULL. Checking m.merchant_name IS NULL (or COALESCE(m.merchant_code, 'UNKNOWN') once empty codes are cleaned) cleanly labels every unmatched merchant 'UNKNOWN'. - Flooring before multiplying: We multiply CAST(FLOOR(t.amount) AS INTEGER) by 3, not FLOOR(3 * t.amount). For 18.60, FLOOR(18.60) * 3 = 18 * 3 = 54, whereas FLOOR(3 * 18.60) = FLOOR(55.80) = 55. - Safe NULL handling in CASE: When a merchant does not match, m.category is NULL. In SQL three-valued logic, NULL = 'Restaurant' evaluates to UNKNOWN (not true), so execution safely falls into ELSE 1.

  4. Mirror the LEFT JOIN in Python with a lookup dictionary

    Now let's write the Python implementation tested by the judge. Scanning the merchants list from start to finish for every single transaction would take O(T * M) time. Instead, we do the exact same thing a database hash join does: scan merchants once to build a dictionary mapping merchant_name -> (merchant_code, category), then look up each transaction in O(1) average time.

    Python dict keys compare strings character-for-character, so "luigi's trattoria" and "Luigi's Trattoria " will not match "Luigi's Trattoria", preserving the exact-match rule automatically. And by keeping the first row seen for any repeated merchant_name, we guarantee every transaction produces exactly one output dictionary.

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def build_merchant_lookup(merchants: List[List]) -> Dict[str, Tuple[str, str]]:
        """Build an exact-match map: merchant_name -> (merchant_code, category)."""
        # merchant_lookup: dict[str, tuple[str, str]],
        # e.g. {"Ramen House": ("MRC-10", "Restaurant"), "Fresh Market": ("MRC-20", "Grocery")}.
        merchant_lookup: Dict[str, Tuple[str, str]] = {}
        for merchant_name, merchant_code, category in merchants:
            # Keep the first row for any repeated merchant_name so a messy CSV
            # never duplicates transactions into multiple output rows.
            if merchant_name not in merchant_lookup:
                merchant_lookup[merchant_name] = (merchant_code, category)
        return merchant_lookup
    
  5. Calculate floored base points and category multipliers

    Next, we loop through transactions in order, look up (merchant_code, category) with fallback ("UNKNOWN", "UNKNOWN"), compute base_points = math.floor(amount), and multiply by 3 if category == "Restaurant" (or 1 otherwise).

    Why use math.floor(amount) instead of int(amount)? Because int() truncates toward zero, while FLOOR rounds down toward negative infinity! On a negative refund like -4.20 (Example 3): - int(-4.20) gives -4 (wrong — truncates toward zero). - math.floor(-4.20) gives -5 (correct — greatest integer <= -4.20), and returns a Python int directly.

    import math
    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def join_transactions_with_merchant_points(
        transactions: List[List], merchants: List[List]
    ) -> List[Dict]:
        # Phase 1: Index merchants by exact merchant_name (mirrors a SQL hash LEFT JOIN).
        merchant_lookup = build_merchant_lookup(merchants)
    
        # Phase 2: Enrich each transaction in input order and compute integer reward points.
        enriched_rows: List[Dict] = []
        for user_id, merchant_name, amount, _transacted_at in transactions:
            # Unmatched merchants still appear in the output with 'UNKNOWN' placeholders.
            if merchant_name in merchant_lookup:
                merchant_code, category = merchant_lookup[merchant_name]
            else:
                merchant_code = "UNKNOWN"
                category = "UNKNOWN"
    
            # math.floor rounds toward -infinity (e.g. 18.60 -> 18 and -4.20 -> -5),
            # whereas int(-4.20) would truncate toward zero and wrongly give -4.
            base_points = math.floor(amount)
    
            # Multiply AFTER flooring: Restaurant earns 3x base_points, all others earn 1x.
            multiplier = 3 if category == "Restaurant" else 1
            final_points = base_points * multiplier
    
            enriched_rows.append({
                "user_id": user_id,
                "merchant_code": merchant_code,
                "category": category,
                "base_points": base_points,
                "final_points": final_points,
            })
    
        return enriched_rows
    
  6. Trace Example 1 and negative refunds step by step

    Let's trace Example 1 with merchants = [["Ramen House", "MRC-10", "Restaurant"], ["Fresh Market", "MRC-20", "Grocery"]]:

    Step 1 — Build merchant_lookup:
      "Ramen House"  -> ("MRC-10", "Restaurant")
      "Fresh Market" -> ("MRC-20", "Grocery")
    
    Step 2 — Process each transaction:
      Row 1: [101, "Ramen House", 18.60, ...]
             lookup hit  -> code="MRC-10", category="Restaurant"
             base_points = floor(18.60) = 18, multiplier = 3 -> final_points = 54
    
      Row 2: [204, "Fresh Market", 53.95, ...]
             lookup hit  -> code="MRC-20", category="Grocery"
             base_points = floor(53.95) = 53, multiplier = 1 -> final_points = 53
    
      Row 3: [101, "Pop-Up Bakery", 7.40, ...]
             lookup miss -> code="UNKNOWN", category="UNKNOWN"
             base_points = floor(7.40)  = 7,  multiplier = 1 -> final_points = 7
    

    And in Example 3, [8, "Book Nook", -4.20, ...] matches ("MRC-50", "Bookstore"), floors -4.20 to -5, and earns -5 final points, while [9, "Unlisted Kiosk", -0.25, ...] misses the lookup, floors -0.25 to -1, and earns -1 final point.

  7. Why SQL beats app post-processing, plus indexing and fuzzy matching

    To address the architecture and data-hygiene parts in an interview, organize your points around three practical pillars:

    1. Why execute LEFT JOIN and CASE inside SQL rather than post-processing in application memory? - Lower network I/O and memory footprint: The database returns only the compact 5-column result set rather than shipping two full raw tables across the wire into Python or Java processes. - Cost-based query optimization: Relational engines automatically choose an efficient join plan (hashing the smaller merchants catalog in memory or probing a B-tree index) and execute compiled C/C++ loops over millions of ledger rows. - Single consistent source of truth: Encapsulating the rule in a SQL view or warehouse model ensures mobile APIs, finance reconciliation, and BI dashboards read identical reward numbers from one atomic snapshot. (Trade-off: if reward tiers evolve into stateful user caps or deeply nested rules, a versioned rules engine becomes easier to unit-test than a sprawling CASE statement.)

    2. Indexes and staging-table cleanup - Indexes: Create a UNIQUE index on merchants(merchant_name) after deduplication — accelerating join probes and guaranteeing one transaction can never fan out into multiple output rows. Add an index on transactions(transacted_at) so incremental batch jobs scan only newly arrived time windows. - Staging cleanup: TRIM leading/trailing whitespace, collapse internal runs of spaces, normalize category casing/plurals ('restaurant', 'Restaurants' -> 'Restaurant'), reject blank names or codes, and route conflicting duplicate merchant names (same name mapped to two different codes) into a quarantine table for manual review.

    3. Reconciling inconsistent merchant_name descriptors - Step A — Deterministic normalization: Canonicalize both tables identically (lowercase, trim, strip punctuation and store IDs so "LUIGI'S TRATTORIA #042" and "Luigi's Trattoria" both normalize to "luigis trattoria") and join on the normalized key first. - Step B — Curated alias mapping: Maintain merchant_aliases(raw_descriptor, merchant_code) for recurring payment-gateway prefixes ("TST* RAMEN HOUSE NYC" -> "MRC-10") so known variants resolve deterministically in O(1) time. - Step C — Similarity scoring + human review + MCCs: Score remaining unmatched descriptors using trigram similarity (such as PostgreSQL pg_trgm) or edit distance, auto-link only above a strict high-precision cutoff, route borderline matches to a review queue that populates merchant_aliases, and combine descriptor signals with structured card Merchant Category Codes (MCCs) whenever available. Because false positives grant 3x points and carry direct financial cost, log every fuzzy match alongside its confidence score.

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import math
    
    
    def build_merchant_lookup(merchants: List[List]) -> Dict[str, Tuple[str, str]]:
        """Build an exact-match map: merchant_name -> (merchant_code, category)."""
        # merchant_lookup: dict[str, tuple[str, str]],
        # e.g. {"Ramen House": ("MRC-10", "Restaurant"), "Fresh Market": ("MRC-20", "Grocery")}.
        merchant_lookup: Dict[str, Tuple[str, str]] = {}
        for merchant_name, merchant_code, category in merchants:
            # Keep the first row for any repeated merchant_name so a messy CSV
            # never duplicates transactions into multiple output rows.
            if merchant_name not in merchant_lookup:
                merchant_lookup[merchant_name] = (merchant_code, category)
        return merchant_lookup
    
    
    def join_transactions_with_merchant_points(
        transactions: List[List], merchants: List[List]
    ) -> List[Dict]:
        # Phase 1: Index merchants by exact merchant_name (mirrors a SQL hash LEFT JOIN).
        merchant_lookup = build_merchant_lookup(merchants)
    
        # Phase 2: Enrich each transaction in input order and compute integer reward points.
        enriched_rows: List[Dict] = []
        for user_id, merchant_name, amount, _transacted_at in transactions:
            # Unmatched merchants still appear in the output with 'UNKNOWN' placeholders.
            if merchant_name in merchant_lookup:
                merchant_code, category = merchant_lookup[merchant_name]
            else:
                merchant_code = "UNKNOWN"
                category = "UNKNOWN"
    
            # math.floor rounds toward -infinity (e.g. 18.60 -> 18 and -4.20 -> -5),
            # whereas int(-4.20) would truncate toward zero and wrongly give -4.
            base_points = math.floor(amount)
    
            # Multiply AFTER flooring: Restaurant earns 3x base_points, all others earn 1x.
            multiplier = 3 if category == "Restaurant" else 1
            final_points = base_points * multiplier
    
            enriched_rows.append({
                "user_id": user_id,
                "merchant_code": merchant_code,
                "category": category,
                "base_points": base_points,
                "final_points": final_points,
            })
    
        return enriched_rows
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine processing thousands of card receipts against a directory of partner stores to calculate loyalty points. Instead of flipping through the entire partner directory from page 1 for every single receipt, you first build an alphabetical tab index keyed by store name — a dictionary in Python, or a hash join in SQL (a join strategy where the database loads the smaller table into an in-memory hash table once and probes it for each row of the larger table in constant average time). As each receipt arrives, you look up its store name in one step: if it is in the index, you copy its merchant code and category; if it is missing, you keep the receipt anyway and stamp 'UNKNOWN' on both fields. That "keep every left-side row even when the right side has no match" rule is called a LEFT JOIN (a SQL join that preserves all rows from the left table and fills unmatched right-table columns with NULL). Finally, you drop fractional cents using floor rounding and triple the floored points whenever the category is 'Restaurant'.

A naive implementation fails in two ways. In Python, scanning all M merchants for each of the T transactions takes O(T * M) comparisons, turning 100,000 transactions across 10,000 merchants into a billion string checks. In SQL, reaching for a default INNER JOIN silently deletes every transaction whose merchant is absent from merchants.csv, losing customer spend instead of tagging it 'UNKNOWN'.

Let's walk through Example 1 with merchants = [["Ramen House", "MRC-10", "Restaurant"], ["Fresh Market", "MRC-20", "Grocery"]]: - First, we index the two merchants: {"Ramen House": ("MRC-10", "Restaurant"), "Fresh Market": ("MRC-20", "Grocery")}. - Transaction 1 (user 101, "Ramen House", 18.60) hits "Ramen House", floors 18.60 to base_points = 18, and triples it because "Restaurant" earns 3x -> final_points = 54. - Transaction 2 (user 204, "Fresh Market", 53.95) hits "Fresh Market", floors 53.95 to base_points = 53, and keeps 1x -> final_points = 53. - Transaction 3 (user 101, "Pop-Up Bakery", 7.40) misses the index, falls back to ("UNKNOWN", "UNKNOWN"), floors 7.40 to base_points = 7, and earns 1x -> final_points = 7.

Complexity

  • Time: O(M + T) average time in Python (and for a SQL hash join), where M is the number of merchant rows and T is the number of transactions. We scan the M merchants once to build merchant_lookup, and then scan the T transactions once, doing one O(1) average-time dictionary lookup and constant-time arithmetic per transaction. (In a SQL engine without hash joins, such as SQLite, an index lookup on merchants(merchant_name) runs in O((M + T) log M) time.)
  • Space: O(M + T) total space — O(M) to hold the unique merchants in merchant_lookup plus O(T) to store the enriched output row for each transaction (O(M) auxiliary space if streaming rows out one by one).

Edge cases

  • Unmatched merchant names: Transactions with no match in merchants are never dropped; they receive merchant_code = 'UNKNOWN', category = 'UNKNOWN', and a 1x multiplier.
  • Empty merchants or empty transactions: If transactions is empty, the output is []. If merchants is empty, every transaction becomes 'UNKNOWN' and earns 1x floored points.
  • Case sensitivity and trailing spaces: Under exact matching, "ramen house" and "Ramen House " do not match "Ramen House" and both fall back to 'UNKNOWN'.
  • Negative amounts (refunds/chargebacks): FLOOR rounds toward negative infinity, not toward zero, so -4.20 floors to -5 and -0.25 floors to -1. A -2.4 refund at a 'Restaurant' produces base_points = -3 and final_points = -9.
  • Sub-dollar and whole-dollar amounts: 0.85 floors to 0 (0 * 3 = 0 points even at a restaurant), while 40 stays 40 (120 at a restaurant).
  • Duplicate merchant_name rows in merchants: Without deduplication, a SQL LEFT JOIN emits two output rows for one transaction and double-awards points. Deduplicating merchants by merchant_name (and keeping the first row in Python) preserves the strict one-row-per-transaction contract.

Common mistakes

  • Using INNER JOIN instead of LEFT JOIN: FROM transactions JOIN merchants ... drops every unmatched merchant row completely instead of labeling it 'UNKNOWN'.
  • Using ROUND or int() truncation instead of FLOOR: ROUND(53.95) gives 54 instead of 53, and truncating toward zero (int(-4.20) in Python or CAST(-4.20 AS INTEGER) in SQLite) gives -4 instead of -5.
  • Multiplying before flooring: Computing FLOOR(amount * 3) on 18.60 yields FLOOR(55.80) = 55, whereas the specification defines base_points = FLOOR(amount) = 18 and final_points = 3 * base_points = 54.
  • Writing inverted NULL-unsafe CASE logic in SQL: Writing CASE WHEN m.category <> 'Restaurant' THEN 1 ELSE 3 END awards 3x points to unmatched 'UNKNOWN' merchants! Why? Because when m.category is NULL, NULL <> 'Restaurant' evaluates to SQL UNKNOWN (not true), falling straight into ELSE 3. Always test the positive condition WHEN m.category = 'Restaurant' THEN 3 ELSE 1.
  • Ignoring database string collation rules: A collation is the set of rules a database uses to compare and sort text strings. MySQL's default _ci (case-insensitive) collations treat 'ramen house' = 'Ramen House' as true and some ignore trailing spaces, silently violating an exact-match requirement unless a case-sensitive binary collation is specified.

Follow-up questions

  • How would you evolve the database schema so temporary category bonus campaigns (such as 5x points on Travel during a holiday window) require zero code deployments? Move multipliers out of hardcoded CASE branches into a rule table category_promotions(category, multiplier, starts_at, ends_at) and LEFT JOIN it on m.category = p.category AND t.transacted_at >= p.starts_at AND t.transacted_at < p.ends_at, falling back to COALESCE(p.multiplier, 1). Launching a campaign becomes a data insert rather than a code release, and historical backfills automatically apply whichever multiplier was active at each transaction's transacted_at timestamp.
  • How can an hourly scheduled pipeline enrich newly arrived transactions safely so retries never double-credit user points? Ensure every ledger event carries a unique transaction_id primary key at ingestion (since one customer can legitimately make two identical purchases in the same second). Track a watermark (the latest timestamp processed by the prior successful run), read a small overlap window before that watermark to catch late-arriving records, and write enriched rows via an upsert (INSERT ... ON CONFLICT (transaction_id) DO UPDATE). That makes each hourly run idempotent (safe to re-execute on the same input while producing the exact same final state).
  • Which automated validation checks should gate each batch run before points are posted to customer balances? Assert row-count conservation (COUNT(*) of enriched rows equals COUNT(*) of input transactions — immediately catching accidental INNER JOIN drops or duplicate-merchant fan-out), verify final_points always equals base_points or 3 * base_points, and alert on spikes in the 'UNKNOWN' merchant fraction. A sudden jump in 'UNKNOWN' share typically indicates an upstream merchants.csv formatting change or a payment processor altering descriptor prefixes.

Follow-up questions

Similar questions

More Bilt Rewards interview questions

All 4 Bilt Rewards questions →