Choosing Which Duplicate to Keep (ORDER BY)

Concepts covered: sqlWindowDedup

Write-time dedup means the deduplication happens as rows land in the target table, not when consumers query it. The target is always in a deduped state. The pattern is MERGE on engines that support it (Snowflake, BigQuery, SQL Server, Oracle, Postgres 15+) or INSERT ... ON CONFLICT on Postgres-family engines, with the dedup key matching the source's natural key. The MERGE pattern for idempotent dedup Reading the pattern The USING clause includes a ROW_NUMBER that picks the most recent row per order_id. The MERGE clause then UPDATES the target if a row exists and the source is newer, or INSERTS if it does not. The 'AND source.rn = 1' filter on each branch ensures only the picked row enters the MERGE. Idempotency holds because rerunning produces the same set of source-rn=1 rows, which produc

About This Interactive Section

This section is part of the Deduplication: Intermediate lesson on DataDriven, a free data engineering interview prep platform. Each section includes explanations, worked examples, and hands-on code challenges that execute in real time. SQL queries run against a live PostgreSQL database. Python runs in a sandboxed Docker container. Data modeling problems validate against interactive schema canvases. All content is framed around what data engineering interviewers actually test at companies like Meta, Google, Amazon, Netflix, Stripe, and Databricks.

How DataDriven Lessons Work

DataDriven combines four interview rounds (SQL, Python, Data Modeling, Pipeline Architecture) with adaptive difficulty and spaced repetition. Easy problems get harder as you improve. Weak concepts resurface until you master them. Your readiness score tracks progress across every topic interviewers test. Every lesson section ends with problems you solve by writing and running real code, not by picking multiple-choice answers.