Deduplicate, MERGE and Package the Load as a Procedure
A PostgreSQL 17 lab: keep the latest staged version of each customer with ROW_NUMBER, apply inserts, updates and deletes to the target with one MERGE, then wrap the load in a parameterised procedure that logs its counts, commits, and can be run twice safely.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Load the target, staging and log tables
- Steps 2 and 3: Find the duplicates and keep the latest version
- Step 4: See why MERGE needs a deduplicated source
- Step 5: Dry-run the real MERGE
- Step 6: Package the load as a procedure
- Step 7: Load the next batch and test the result
- Check your understanding
- Apply it
- Review prompt
Lessons of Advanced SQL
- Window Functions: Partitions, Order and Frames Concept · 25 min
- Lab: Retention, Running Totals and Gaps-and-Islands Lab · 30 min
- Readable Step-by-Step Queries with CTEs and Recursion Worked example · 25 min
- Multi-Level Reports, Pivots and Result-Set Comparisons Lab · 25 min
- Deduplicate, MERGE and Package the Load as a Procedure Lab · 30 min
- Check: Analytical Query Challenge Knowledge check · 8 questions
What you will learn
- Keep the latest record per key with ROW_NUMBER-based deduplication, apply changes to a target table with MERGE, and package the load as a parameterized SQL function or procedure.
Prerequisites: SQL Fundamentals
01. Goal and setup
Most warehouses receive changes, not finished tables. A CRM export lands every night in a staging table, a plain table that holds raw incoming rows, and a load job applies those rows to the target table that reports read. The incoming rows are messy: a customer can appear several times in one batch, the same row can be delivered twice, and some rows say "this customer was deleted". In this lab you build that load step by step and finish with a procedure, CALL load_customers('2026-03-01'), that a scheduler could run every night.
You need the sql-lab container from the earlier labs (PostgreSQL 17; tested with 17.11). MERGE exists since PostgreSQL 15; its RETURNING clause and the merge_action() function used below need PostgreSQL 17. Work in a folder load-lab/.
load-lab/
├── seed.sql step 1: target, staging and log tables
├── inspect.sql steps 2 and 3: duplicates and ROW_NUMBER
├── naive.sql step 4: MERGE on the raw batch
├── dry_run.sql step 5: MERGE on the deduplicated batch, rolled back
├── procedure.sql step 6: the load_customers procedure
└── test.sql step 7: next batch and a result test02. Step 1: Load the target, staging and log tables
The target customers starts with three customers. staging_customers holds two nightly batches, marked by batch_date. Each row has an operation, op: U for "insert or update" and D for "delete". ingest_seq records the order in which rows arrived; you will need it to break ties. Read the 1 March batch closely: customer 1 changed twice, customer 4 was delivered twice with identical values, customer 3 was deleted, and customer 2 arrived again with no change at all. load_log will record what each run did.
CREATE TABLE customers (
customer_id int PRIMARY KEY,
email text NOT NULL,
city text NOT NULL,
updated_at timestamp NOT NULL
);
INSERT INTO customers VALUES
(1, '[email protected]', 'Leeds', '2026-02-20 08:00'),
(2, '[email protected]', 'York', '2026-02-21 08:00'),
(3, '[email protected]', 'Bath', '2026-02-22 08:00');
CREATE TABLE staging_customers (
ingest_seq bigint GENERATED ALWAYS AS IDENTITY,
batch_date date NOT NULL,
op char(1) NOT NULL CHECK (op IN ('U', 'D')), -- upsert or delete
customer_id int NOT NULL,
email text,
city text,
updated_at timestamp NOT NULL
);
INSERT INTO staging_customers (batch_date, op, customer_id, email, city, updated_at)
VALUES
('2026-03-01', 'U', 1, '[email protected]', 'Leeds', '2026-03-01 09:00'),
('2026-03-01', 'U', 1, '[email protected]', 'Hull', '2026-03-01 10:00'),
('2026-03-01', 'U', 4, '[email protected]', 'Exeter', '2026-03-01 09:30'),
('2026-03-01', 'U', 4, '[email protected]', 'Exeter', '2026-03-01 09:30'),
('2026-03-01', 'D', 3, NULL, NULL, '2026-03-01 11:00'),
('2026-03-01', 'U', 2, '[email protected]', 'York', '2026-03-01 12:00'),
('2026-03-02', 'U', 2, '[email protected]', 'York', '2026-03-02 09:00'),
('2026-03-02', 'U', 5, '[email protected]', 'Leeds', '2026-03-02 09:15');
CREATE TABLE load_log (
run_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
batch_date date NOT NULL,
inserted int NOT NULL,
updated int NOT NULL,
deleted int NOT NULL
);
SELECT batch_date, count(*) AS staged_rows FROM staging_customers
GROUP BY batch_date ORDER BY batch_date;docker exec sql-lab psql -U postgres -X -q -c "SET client_min_messages = warning" \
-c "DROP DATABASE IF EXISTS crm" -c "CREATE DATABASE crm"
docker exec -i sql-lab psql -U postgres -d crm -X -q < seed.sql batch_date | staged_rows
------------+-------------
2026-03-01 | 6
2026-03-02 | 2
(2 rows)03. Steps 2 and 3: Find the duplicates and keep the latest version
First measure the problem. The first query lists every customer with more than one row in the 1 March batch, and how many distinct timestamps those rows have. The second query numbers each customer's rows from newest to oldest in two ways, with row_number() and with rank(), so you can see which one is safe for deduplication.
SELECT customer_id, count(*) AS versions, count(DISTINCT updated_at) AS distinct_times
FROM staging_customers
WHERE batch_date = '2026-03-01'
GROUP BY customer_id
HAVING count(*) > 1
ORDER BY customer_id;
SELECT customer_id, ingest_seq, city, updated_at,
row_number() OVER w AS rn,
rank() OVER w AS rnk
FROM staging_customers
WHERE batch_date = '2026-03-01'
WINDOW w AS (PARTITION BY customer_id ORDER BY updated_at DESC)
ORDER BY customer_id, ingest_seq;docker exec -i sql-lab psql -U postgres -d crm -X -q < inspect.sql customer_id | versions | distinct_times
-------------+----------+----------------
1 | 2 | 2
4 | 2 | 1
(2 rows)
customer_id | ingest_seq | city | updated_at | rn | rnk
-------------+------------+--------+---------------------+----+-----
1 | 1 | Leeds | 2026-03-01 09:00:00 | 2 | 2
1 | 2 | Hull | 2026-03-01 10:00:00 | 1 | 1
2 | 6 | York | 2026-03-01 12:00:00 | 1 | 1
3 | 5 | | 2026-03-01 11:00:00 | 1 | 1
4 | 3 | Exeter | 2026-03-01 09:30:00 | 1 | 1
4 | 4 | Exeter | 2026-03-01 09:30:00 | 2 | 1
(6 rows)Customer 1 has two real versions; the one from 10:00, with city Hull, is the latest. Customer 4 has two rows with the same timestamp. rank() gives both rank 1, so "keep rank 1" would keep both and the duplicate would survive. row_number() always gives exactly one row the number 1, which is what deduplication needs. But look at which row got 1 for customer 4: with only updated_at in the ORDER BY, PostgreSQL may pick either tied row, and a later run may pick the other. When tied rows can differ in other columns, that makes the load non-deterministic. The fix is a tie-breaker that is unique and meaningful. Here, ingest_seq DESC means "the row that arrived last wins". From now on the window is ORDER BY updated_at DESC, ingest_seq DESC.
04. Step 4: See why MERGE needs a deduplicated source
MERGE joins a source (here, the staging rows) to a target (the customers) with an ON condition, then runs a different action for each source row depending on whether it matched: WHEN MATCHED THEN UPDATE or DELETE, WHEN NOT MATCHED THEN INSERT. It is the standard SQL statement for applying changes, and it replaces separate UPDATE, INSERT and DELETE statements that each scan the data. Try it first on the raw batch.
MERGE INTO customers t
USING (SELECT * FROM staging_customers WHERE batch_date = '2026-03-01') s
ON t.customer_id = s.customer_id
WHEN MATCHED THEN
UPDATE SET email = s.email, city = s.city, updated_at = s.updated_at
WHEN NOT MATCHED THEN
INSERT VALUES (s.customer_id, s.email, s.city, s.updated_at);docker exec -i sql-lab psql -U postgres -d crm -X -q < naive.sqlERROR: MERGE command cannot affect row a second time
HINT: Ensure that not more than one source row matches any one target row.Two staging rows for customer 1 match the same target row, and MERGE refuses to change one row twice, because the source has no defined order that would say which change wins. The whole statement fails and nothing is changed. Note also two other problems this naive version would have had: it treats the delete row for customer 3 as an update and would try to set email to NULL, and it rewrites customer 2 although nothing changed.
05. Step 5: Dry-run the real MERGE
The real statement takes its source from a CTE that keeps rn = 1, and it has three branches, checked in order for each source row:
- matched and
op = 'D': delete the customer; - matched and something changed: update.
(t.email, t.city) IS DISTINCT FROM (s.email, s.city)compares the two pairs and treats NULLs as comparable values, unlike<>; - not matched and
op = 'U': insert.
A source row that fits no branch is skipped. RETURNING merge_action() reports what happened to each row. Wrapping the MERGE in another CTE lets you sort that report, and BEGIN ... ROLLBACK turns the whole file into a dry run: you see the effect, then undo it.
BEGIN;
WITH latest AS (
SELECT *, row_number() OVER (PARTITION BY customer_id
ORDER BY updated_at DESC, ingest_seq DESC) AS rn
FROM staging_customers
WHERE batch_date = '2026-03-01'
), changes AS (
MERGE INTO customers t
USING (SELECT * FROM latest WHERE rn = 1) s
ON t.customer_id = s.customer_id
WHEN MATCHED AND s.op = 'D' THEN
DELETE
WHEN MATCHED AND (t.email, t.city) IS DISTINCT FROM (s.email, s.city) THEN
UPDATE SET email = s.email, city = s.city, updated_at = s.updated_at
WHEN NOT MATCHED AND s.op = 'U' THEN
INSERT VALUES (s.customer_id, s.email, s.city, s.updated_at)
RETURNING merge_action() AS action, s.customer_id, s.city
)
SELECT * FROM changes ORDER BY customer_id;
ROLLBACK;docker exec -i sql-lab psql -U postgres -d crm -X -q < dry_run.sql action | customer_id | city
--------+-------------+--------
UPDATE | 1 | Hull
DELETE | 3 |
INSERT | 4 | Exeter
(3 rows)Three actions, one per real change: customer 1 moves to Hull, customer 3 is deleted, customer 4 is inserted once. Customer 2 is matched but unchanged, so no branch fires. Skipping no-op updates matters: PostgreSQL does not notice on its own that an update sets the same values, so it would write a new row version, change updated_at and inflate the "updated" count. PostgreSQL 17 also offers WHEN NOT MATCHED BY SOURCE, which acts on target rows that are missing from the source; use it only when each batch is a full snapshot, never with a batch of changes like this one, or it would delete every customer who simply did not change.
06. Step 6: Package the load as a procedure
A scheduler should not paste SQL. It should call one named unit with one parameter, the batch date. PostgreSQL offers two kinds of named units. A function (CREATE FUNCTION, called with SELECT) returns a value and always runs inside the caller's transaction. A procedure (CREATE PROCEDURE, called with CALL, since PostgreSQL 11) returns nothing by default but may run COMMIT and ROLLBACK inside its body. A load that should commit its work and its log entry together, and could commit after each of several batches, is a procedure.
The body below is written in PL/pgSQL, PostgreSQL's procedural language. It runs the same MERGE with the batch date as a parameter, counts the actions with count(*) FILTER (...) into three variables, writes one log row and commits. The file then calls it twice for the same date.
CREATE PROCEDURE load_customers(p_batch date)
LANGUAGE plpgsql
AS $$
DECLARE
n_ins int; n_upd int; n_del int;
BEGIN
WITH latest AS (
SELECT *, row_number() OVER (PARTITION BY customer_id
ORDER BY updated_at DESC, ingest_seq DESC) AS rn
FROM staging_customers
WHERE batch_date = p_batch
), changes AS (
MERGE INTO customers t
USING (SELECT * FROM latest WHERE rn = 1) s
ON t.customer_id = s.customer_id
WHEN MATCHED AND s.op = 'D' THEN
DELETE
WHEN MATCHED AND (t.email, t.city) IS DISTINCT FROM (s.email, s.city) THEN
UPDATE SET email = s.email, city = s.city, updated_at = s.updated_at
WHEN NOT MATCHED AND s.op = 'U' THEN
INSERT VALUES (s.customer_id, s.email, s.city, s.updated_at)
RETURNING merge_action() AS action
)
SELECT count(*) FILTER (WHERE action = 'INSERT'),
count(*) FILTER (WHERE action = 'UPDATE'),
count(*) FILTER (WHERE action = 'DELETE')
INTO n_ins, n_upd, n_del
FROM changes;
INSERT INTO load_log (batch_date, inserted, updated, deleted)
VALUES (p_batch, n_ins, n_upd, n_del);
COMMIT;
END;
$$;
CALL load_customers('2026-03-01');
CALL load_customers('2026-03-01');
SELECT * FROM load_log ORDER BY run_id;
SELECT * FROM customers ORDER BY customer_id;docker exec -i sql-lab psql -U postgres -d crm -X -q < procedure.sql run_id | batch_date | inserted | updated | deleted
--------+------------+----------+---------+---------
1 | 2026-03-01 | 1 | 1 | 1
2 | 2026-03-01 | 0 | 0 | 0
(2 rows)
customer_id | email | city | updated_at
-------------+-----------------+--------+---------------------
1 | [email protected] | Hull | 2026-03-01 10:00:00
2 | [email protected] | York | 2026-02-21 08:00:00
4 | [email protected] | Exeter | 2026-03-01 09:30:00
(3 rows)The second run logged 0, 0 and 0. The batch is now fully applied, so every branch condition is false: customer 1 already lives in Hull, customer 4 exists, and customer 3 is no longer there to delete. A load that gives the same final state however many times it runs is idempotent, so a failed night can be re-run safely.
07. Step 7: Load the next batch and test the result
Load 2 March, then test the target against the rows you expect, written as a VALUES list. The two EXCEPT queries return the rows that differ in either direction, so an empty result means the table is exactly right. The file then shows the limits of the two kinds of named unit: a function that tries to commit, and the procedure called inside an explicit transaction block.
CALL load_customers('2026-03-02');
WITH expected(customer_id, email, city) AS (VALUES
(1, '[email protected]', 'Hull'),
(2, '[email protected]', 'York'),
(4, '[email protected]', 'Exeter'),
(5, '[email protected]', 'Leeds')
), actual AS (
SELECT customer_id, email, city FROM customers
)
SELECT 'missing' AS problem, * FROM (TABLE expected EXCEPT TABLE actual) m
UNION ALL
SELECT 'unexpected', * FROM (TABLE actual EXCEPT TABLE expected) u;
SELECT * FROM load_log ORDER BY run_id;
CREATE FUNCTION log_and_commit() RETURNS void
LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO load_log (batch_date, inserted, updated, deleted)
VALUES ('2026-03-02', 0, 0, 0);
COMMIT;
END;
$$;
SELECT log_and_commit();
BEGIN;
CALL load_customers('2026-03-02');
ROLLBACK;docker exec -i sql-lab psql -U postgres -d crm -X -q < test.sql problem | customer_id | email | city
---------+-------------+-------+------
(0 rows)
run_id | batch_date | inserted | updated | deleted
--------+------------+----------+---------+---------
1 | 2026-03-01 | 1 | 1 | 1
2 | 2026-03-01 | 0 | 0 | 0
3 | 2026-03-02 | 1 | 1 | 0
(3 rows)
ERROR: invalid transaction termination
CONTEXT: PL/pgSQL function log_and_commit() line 5 at COMMIT
ERROR: invalid transaction termination
CONTEXT: PL/pgSQL function load_customers(date) line 30 at COMMITThe test returned no rows, so the table matches. Run 3 inserted Eve and updated Ben. Both errors are "invalid transaction termination": a function cannot commit because it is part of the statement that called it, and even a procedure cannot commit when the caller has already opened a transaction with BEGIN. Schedule CALL load_customers(...) on its own, outside any transaction block.
A stored procedure lives inside the database, so it is easy to call but easy to change without review. Many teams now keep load logic as version-controlled SQL models instead, for example dbt incremental models that compile to a similar MERGE, with tests in the same repository. The SQL stays the same; what changes is where it is reviewed, tested and deployed.
08. Check your understanding
09. Apply it
The practice project ends with a deduplicated customer table maintained by a MERGE wrapped in a stored procedure, with tests. Take this lab there:
- Add a
namecolumn to the target and the staging table, and include it in the change test. - Make
load_customersrefuse to run for a date that has no staged rows, withRAISE EXCEPTION. - Write a second test that runs the same batch twice and checks that the second log row is 0, 0, 0.
- Write a parameterised SQL function,
customers_changed_since(p_ts timestamp), that returns the customers updated after a given time, for downstream jobs.
10. Review prompt
Without looking back, explain:
- why deduplication uses
row_number()with a tie-breaker, notrank(); - what MERGE does with a source row that matches no
WHENbranch, and why it rejects two source rows for one target row; - why the change test
IS DISTINCT FROMis part of the update branch; - the difference between a function and a procedure in PostgreSQL, and when a
CALLstill cannot commit; - what makes the load idempotent.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.