Auditing a Credit-Card Ledger: Validation Rules and Failing-Row Queries
SQL & DataModel answerLast updated
Design a layered set of data quality checks over transactions and vendors tables, with SQL for the failing rows.
You are responsible for the health of a credit-card ledger stored in two relational tables.
transactions
| column | type | description |
|---|---|---|
transaction_id | integer | Unique ID for a transaction. |
user_id | integer | Unique ID for a customer. |
vendor_id | integer | Unique ID for a vendor. |
transaction_time | timestamp | Time when the transaction was recorded. |
transaction_dollars | numeric | Dollar amount of the transaction. |
transaction_type | text | Transaction type, such as PURCHASE or REFUND. |
refund_transaction_id | integer | For a REFUND, the transaction_id of the original PURCHASE. |
vendors
| column | type | description |
|---|---|---|
vendor_id | integer | Unique ID for a vendor. |
city | text | City where the vendor is located. |
state_province | text | State or province where the vendor is located. |
country | text | Two-letter country code. |
Propose at least five data quality checks or validations for these tables. Consider integrity constraints, referential integrity, refund logic, invalid values, missing data, and anomaly detection. For at least two checks, provide SQL that returns the failing rows or failing keys.
Hints
Hint 1
Write each check as a query that returns the bad rows, so an empty result is a pass — and separate hard rules (fail the pipeline) from statistical rules (warn only).
Hint 2
Refund checks are multi-part: the link must be present, point to a real PURCHASE, share the same user and vendor, come after the purchase, and never exceed the purchase amount in total.
Hint 3
For anomaly detection, compare today's volume against a trailing window using a window function; state explicitly any sign or cents-rounding assumptions.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Auditing a Credit-Card Ledger: Validation Rules and Failing-Row Queries
Framing the answer
I'd organize the checks by the class of failure they catch, and write each as a query that returns the offending rows or keys — an empty result means the check passed. That gives a uniform operating pattern: run the query, count rows, compare to a threshold, then either block the pipeline (hard rule) or page someone (soft rule). I'd split the layers as follows:
- Integrity constraints — keys unique and non-null.
- Referential integrity — every foreign key resolves.
- Business logic — refunds behave like refunds.
- Domain validity — enums, signs, country codes, timestamps are legal.
- Completeness — required fields present; null rates stable.
- Anomalies — volumes and amounts look like history.
Layers 1–5 are deterministic. A violation is a bug, so the batch should fail loudly. Layer 6 is statistical, so it should warn, not block.
The checks
1. Primary key uniqueness and non-null. transaction_id must be unique and not null; same for vendors.vendor_id.
SELECT transaction_id, COUNT(*) AS n
FROM transactions
GROUP BY transaction_id
HAVING transaction_id IS NULL OR COUNT(*) > 1;
Duplicates almost always mean an ingestion job replayed a batch, which double-counts revenue everywhere downstream.
2. Referential integrity. Every transactions.vendor_id must exist in vendors.
SELECT t.transaction_id, t.vendor_id
FROM transactions t
LEFT JOIN vendors v ON v.vendor_id = t.vendor_id
WHERE v.vendor_id IS NULL;
The same anti-join applies to user_id if a users table exists.
3. Refund linkage. A REFUND must have a non-null refund_transaction_id, that ID must point to a real PURCHASE, the purchase must share the same user_id and vendor_id, and the refund must not precede the purchase.
SELECT r.transaction_id AS refund_id,
r.refund_transaction_id,
CASE
WHEN r.refund_transaction_id IS NULL THEN 'missing_link'
WHEN p.transaction_id IS NULL THEN 'orphan_refund'
WHEN p.transaction_type <> 'PURCHASE' THEN 'links_to_non_purchase'
WHEN p.user_id <> r.user_id
OR p.vendor_id <> r.vendor_id THEN 'party_mismatch'
WHEN r.transaction_time < p.transaction_time THEN 'refund_before_purchase'
END AS failure_reason
FROM transactions r
LEFT JOIN transactions p ON p.transaction_id = r.refund_transaction_id
WHERE r.transaction_type = 'REFUND'
AND ( r.refund_transaction_id IS NULL
OR p.transaction_id IS NULL
OR p.transaction_type <> 'PURCHASE'
OR p.user_id <> r.user_id
OR p.vendor_id <> r.vendor_id
OR r.transaction_time < p.transaction_time);
The converse also matters: a PURCHASE must have a null refund_transaction_id, otherwise the column is being abused as a general pointer.
4. No over-refunding. Total refunds against one purchase must not exceed the purchase amount — this covers partial and repeated refunds. The schema doesn't state whether refunds are stored as negative or positive amounts, so I compare absolute values and say that assumption out loud.
SELECT p.transaction_id,
p.transaction_dollars AS purchase_amount,
SUM(ABS(r.transaction_dollars)) AS total_refunded
FROM transactions p
JOIN transactions r
ON r.refund_transaction_id = p.transaction_id
AND r.transaction_type = 'REFUND'
WHERE p.transaction_type = 'PURCHASE'
GROUP BY p.transaction_id, p.transaction_dollars
HAVING SUM(ABS(r.transaction_dollars)) > ABS(p.transaction_dollars) + 0.005;
The + 0.005 gives a half-cent tolerance for rounding noise.
5. Domain validity.
transaction_type∈('PURCHASE','REFUND')— watch for case and whitespace variants like'purchase ', which the enum check catches only if you trim and upper-case first.transaction_dollarsis non-zero and respects the agreed sign convention (e.g., purchases positive, refunds negative or positive but consistent).- At most 2 decimal places, and under a sanity cap such as $1M.
transaction_timeis not null, not in the future beyond a few minutes of clock skew, and not before the business launched.vendors.countrymatches^[A-Z]{2}$and appears in an ISO 3166 reference table.state_provinceis consistent withcountry.
SELECT transaction_id, transaction_type, transaction_dollars, transaction_time
FROM transactions
WHERE transaction_type IS NULL
OR UPPER(TRIM(transaction_type)) NOT IN ('PURCHASE', 'REFUND')
OR transaction_dollars IS NULL
OR transaction_dollars = 0
OR (transaction_type = 'PURCHASE' AND transaction_dollars <= 0)
OR transaction_dollars <> ROUND(transaction_dollars, 2)
OR ABS(transaction_dollars) > 1000000
OR transaction_time IS NULL
OR transaction_time > NOW() + INTERVAL '5 minutes';
6. Completeness. A hard rule: user_id, vendor_id, transaction_time, transaction_dollars must never be null. A soft rule: track each column's daily null rate against its baseline — a jump from 0.1% to 8% is a broken upstream field even when the column is nullable.
7. Near-duplicate events. Different transaction_ids can describe the same event: same user_id, vendor_id, amount, within a few seconds. Usually retry duplicates — flag for review, don't fail, because some are legitimate.
8. Volume and amount anomalies. Compare daily row counts and dollar totals against a trailing window.
WITH daily AS (
SELECT DATE(transaction_time) AS d,
COUNT(*) AS n,
SUM(transaction_dollars) AS dollars
FROM transactions
GROUP BY 1
), stats AS (
SELECT d, n, dollars,
AVG(n) OVER w AS mean_n,
STDDEV_SAMP(n) OVER w AS sd_n
FROM daily
WINDOW w AS (ORDER BY d ROWS BETWEEN 28 PRECEDING AND 1 PRECEDING)
)
SELECT d, n, mean_n, sd_n
FROM stats
WHERE sd_n > 0 AND ABS(n - mean_n) / sd_n > 3;
Worth extending: run this per vendor or per country to catch one integration going dark, monitor the refund-to-purchase ratio, and check freshness — MAX(transaction_time) should sit within the expected lag of the load time.
Why this structure holds up
Each check states an invariant, and the query is exactly the set of rows that violate it. So an empty result proves the invariant for the data scanned, and every check spells out null handling explicitly (IS NULL, LEFT JOIN … IS NULL), which is where hand-written validations usually go wrong: NULL <> 'PURCHASE' evaluates to UNKNOWN, silently dropping rows unless you use IS NOT DISTINCT FROM or explicit null branches.