MEDIUMAI Generated Practice• Data Analyst

Detect Rapid Multi‑Zip Card Activity with Window Functions

A fintech unicorn wants to flag potentially fraudulent credit cards that exhibit a velocity anomaly: more than three transactions occurring in different zip codes within any rolling 20‑minute window. For each flagged transaction you must return the card identifier, transaction timestamp, the zip code of that transaction, and the count of distinct zip codes seen in the preceding 20 minutes (including the current one). The solution must:

  • Use PostgreSQL‑compatible window functions.
  • Correctly handle NULL zip codes by treating them as a distinct placeholder (e.g., 'UNKNOWN') using COALESCE.
  • Properly rank ties when multiple transactions have the same distinct‑zip count (use DENSE_RANK or similar).
  • Return only rows where the distinct‑zip count exceeds 3.

Schema (presented as markdown tables for clarity):

TableColumns
cardscard_id INTEGER PK, card_number VARCHAR(16), holder_name VARCHAR(100)
transactionstxn_id INTEGER PK, card_id INTEGER FK → cards(card_id), transaction_ts TIMESTAMP NOT NULL, amount DECIMAL(10,2), zip_code VARCHAR(10) (may be NULL)

Write a single SQL query that solves the problem using window functions, handling the edge cases described.

Execution Sandbox:

Your query executes inside an isolated in-memory PostgreSQL engine (PGlite WebAssembly). You have full access to standard PostgreSQL aggregations, window functions, and CTEs.

Standard SQL (ANSI)|Ln 1, Col 1
⌘↵ Run Query
Ready to execute. Press Run (⌘+Enter)
Write your query and click “Run” or press ⌘+Enter to inspect output.