Explain the SQL query that reconciles transactions from tables txn_a and txn_b.
💡 Model Answer
The query uses a common table expression (CTE) named all_txns to combine rows from two source tables, txn_a and txn_b, tagging each row with a source identifier ('A' or 'B'). The UNION ALL preserves duplicates and keeps the source column. In the second CTE, diffs, the query pivots the data back to a wide format: for each txn_id it selects the notion_a and int_a values from both sources using MAX(CASE WHEN src='A' THEN notion_a END) and similar expressions for source 'B'. This effectively aligns the two rows side‑by‑side so that you can compare the values. The final SELECT (not shown in the snippet) would typically compute the difference between the two sources, flag mismatches, or produce a reconciliation report. The use of MAX with CASE is a common pattern to pivot a one‑to‑one relationship when you know there will be at most one row per source per txn_id. The query is efficient because it scans each source table only once and uses simple aggregations to align the data.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500