Skip to content

A scenario for a data engineer · Senior and up

The primary key did not stop the duplicates

Query · Analytics
Monday, 14:05

The customers table in Unity Catalog on Databricks has a PRIMARY KEY on customer id. An analyst finds the same customer id on two rows and asks how the key let that happen.

What do you do?

Tap the one you would do. The answer opens below.

Show the best call

Explain that the key is not enforced, remove the duplicates, and make the load a MERGE on customer id so that a rerun cannot add one.

The table has one row per customer again, and a rerun of the load can no longer add a second.

Why

On Databricks, primary key, foreign key and unique constraints are informational. They describe how tables relate, and with the RELY option the optimizer trusts them, but they do not stop a duplicate. Only NOT NULL and CHECK constraints are enforced. Uniqueness has to come from how the table is written, for example a MERGE on the key from a batch that holds each key once.

Read it in the Databricks docs (opens in a new tab)

The other two

Works, at a price. Remove the duplicates, and add a nightly job that looks for new ones and sends an alert.
You hear about duplicates the morning after. They still get in, and reports read them until then.
A poor call. Drop the key and declare it again, so that it takes effect.
Nothing changes. The key was never checking anything.

The words in this scenario

Unity Catalog.
The part of Databricks that governs data: who may see and change which tables and files, where data came from, and who did what. In the docs (opens in a new tab)
MERGE.
One statement that compares new rows with a table by a key: rows that match are updated or deleted, rows that do not are inserted. In the docs (opens in a new tab)

Go deeper on brickster.ai

More scenarios

Had one like this at work? Send it to us: the best tickets come from real incidents.

Added on . Checked against the Databricks documentation on . brickster.ai is independent and is not affiliated with Databricks.