What Is a Surrogate Key? Surrogate Key vs Natural Key, With SQL

A surrogate key is an identifier that a database or data warehouse generates for a row: it has no business meaning and exists only so other tables can join to that row. A natural key is the identifier the business already uses, such as a customer number or a SKU. Warehouses join on the surrogate key and keep the natural key as an attribute, because natural keys change, repeat when history is tracked and collide across source systems.

Last updated: Proudly published by: Jeff Wahl15 min read

What is a surrogate key?

A surrogate key is a value that a database or warehouse generates to identify a row, and it does nothing else. It carries no business meaning and no person ever types it. It stays the same for as long as the row exists, and it usually takes 1 of 3 forms: an integer from a sequence or identity column, a hash of the row's natural key, or a UUID.

The natural key is the identifier the business already uses: a customer number from the CRM, an email address, an order number, a SKU. Take a customer the source system calls C-1042. In the warehouse's dim_customer table that customer's row gets customer_key = 7. The 7 says nothing about the customer. Its job is to give fact tables 1 narrow, stable column to join on, while C-1042 stays on the row as an ordinary attribute so that later loads can find the row again.

The term goes back to a 1976 paper that Hall wrote with Owlett and Todd. Ralph Kimball made it standard practice in data warehousing, defining a surrogate key in 1998 as an artificial or synthetic key used as a substitute for a natural key. Synthetic key and artificial key are other names for the same thing, as is meaningless key.

Surrogate key vs natural key at a glance

Surrogate key
  • Assigned byWarehouse or database
  • Business meaningNone
  • Changes over timeNever
  • Identifies1 row
  • Typical typeBIGINT or 128-bit hash
  • Shown to business usersNo
Natural key
  • Assigned bySource system
  • Business meaningYes
  • Changes over timeWhen the business says
  • Identifies1 real-world thing
  • Typical typeText, often composite
  • Shown to business usersYes

Surrogate key vs natural key: what each one is for

A natural key answers which real-world thing a row describes. A surrogate key answers which row it is. The 2 answers are the same until a table keeps history, takes rows from more than 1 source, or outlives a change to the business identifier. In a warehouse all 3 happen sooner or later.

The natural key has real advantages. It already exists, a person can read it, a load needs no lookup to use it, and a unique constraint on it stops duplicates. Its weakness is that someone else decides what it is. The Kimball Group says natural keys are subject to business rules outside the control of the warehouse, and gives the example of an employee who resigns and is rehired under a new employee number. Email addresses change and SKUs are retired and reused. A 3 column composite key puts 3 predicates in every join.

The surrogate key has costs too. It is an extra column, every fact load has to translate natural keys into it, and a bare number is harder to debug than a customer id. It also prevents nothing by itself: load the same customer twice and each copy gets its own key, and both rows look valid.

The surrogate key replaces the natural key as the join column, and the natural key remains the uniqueness rule. Keep the natural key on the row and keep it unique, per version when the table tracks history. Use the natural key alone as the primary key only when it is a single column from 1 source, and only if it never changes and has 1 row per thing. A staging table usually meets that standard and a warehouse dimension rarely does.

Prepare for the interview
01 / Open invite
02min.

Know Surrogate Keys the way the interviewer who asks it knows it.

a Surrogate Keys query, the same shape a screen would give you.
The diff against expected. Where ties broke. What you missed.
sandbox
1fact_orders
2 order_id bigint PK
3 customer_sk bigint FK
4 order_date date SCD2
5
Execute your solution0.4s avg.
UberInterview question
Solve a Surrogate Keys problem

Why a dimension that keeps history needs a surrogate key

A natural key identifies a customer. A dimension that tracks changes holds more than 1 row per customer, so the natural key stops being unique and cannot be the primary key. This is the first reason the Kimball Group gives for surrogate keys: there will be multiple dimension rows for a natural key once changes are tracked over time.

Customer C-1042 lives in Austin and places 3 orders, then moves to Denver and places 2 more. A type 2 slowly changing dimension keeps both versions: the Austin row under customer_key 7 and the Denver row under customer_key 19. Both rows carry C-1042. Each order stores the surrogate key of the version in effect when it was placed, so revenue by city still credits 3 orders to Austin and 2 to Denver.

Customer C-1042 has 2 rows in dim_customer: Austin under surrogate key 7 and Denver under surrogate key 19. In fct_orders, the 3 orders placed before the move point at key 7 and the 2 placed after it point at key 19Customer C-1042 has 2 rows in dim_customer: Austin under surrogate key 7 and Denver under surrogate key 19. In fct_orders, the 3 orders placed before the move point at key 7 and the 2 placed after it point at key 19

Join the same 5 orders on the natural key instead and every order matches both rows. The query returns 10 rows, each order is counted once in Austin and once in Denver, and revenue doubles. Adding the order date to the join fixes the count and turns every join into a range predicate, which is why Kimball's guidance prefers anonymous integer keys over natural keys with dates appended. The mechanics of closing 1 version and opening another are covered in SCD type 2 in SQL.

The natural key still has a job here. COUNT(DISTINCT customer_key) counts versions and returns 2 for this customer. Counting customers means grouping by C-1042, which Kimball calls the durable key: the 1 identifier that stays fixed while surrogate keys accumulate.

Why data warehouses use surrogate keys

The Kimball Group's rule for dimension surrogate keys is that the warehouse must claim control of the primary keys of all dimensions. Tracking history is 1 reason. Source systems that reuse their keys, several sources describing the same thing, and the width of the key column are 3 more, and they apply even to a dimension that never keeps a second version of a row.

Source keys belong to the source. Kimball's 1998 article describes production keys as generated and formatted according to the dictates of production, which also decide when a key is updated or deleted and whether it is recycled and reused. When an operational system purges a closed account and later issues its number to a new customer, a warehouse keyed on that number attaches the new customer to the old customer's facts.

Several sources describe the same thing. The CRM and the billing system each have a customer id, the 2 schemes overlap or disagree, and the same person may hold 1 of each. A warehouse key gives the model 1 row to conform both onto, with each source id kept as an attribute.

Fact tables are long, so key width matters. Kimball's arithmetic still holds: on a fact table of 1 billion rows, every byte in a row is a gigabyte of storage. Before compression, a BIGINT key column takes 8 GB, a 16 byte binary hash takes 16 GB, and an MD5 hash stored as 32 hex characters takes 32 GB, 4 times the integer. A fact table in a star schema carries 1 such column per dimension.

A star schema joined on surrogate keys

fct_orders
order_idPKBIGINT
customer_keyFKBIGINT
product_keyFKBIGINT
date_keyFKINT
amountDECIMAL
dim_customer
customer_keyPKBIGINT
customer_idVARCHAR
cityVARCHAR
valid_fromTIMESTAMP
valid_toTIMESTAMP
is_currentBOOLEAN
dim_product
product_keyPKBIGINT
skuVARCHAR
categoryVARCHAR
dim_date
date_keyPKINT
full_dateDATE
is_weekendBOOLEAN

fct_orders joins each dimension on its surrogate key. The natural keys customer_id and sku stay on the dimensions as attributes, and date_key is the 1 key allowed to carry meaning

How to generate a surrogate key: sequence, hash or UUID

A sequence or identity column hands each new row the next integer. It is the form Kimball describes, simple integers assigned in sequence starting with 1, and it's the narrowest key available. It has 2 costs. The number exists only in the dimension, so a fact load must look it up there. And the number depends on load order, so a dimension that is dropped and rebuilt gets different keys unless the old ones are persisted and reused.

A hash key is computed from the natural key, plus the version's start time in a type 2 dimension. The same input produces the same key in every environment and on every run, including across parallel workers, which is why it suits pipelines that rebuild tables. In dbt, dbt_utils.generate_surrogate_key casts each column to a string, replaces a NULL with the placeholder _dbt_utils_surrogate_key_null_, joins the columns with a - and hashes the result, with MD5 on the default adapters. The cost is width, and a column of hashes is random, so it compresses poorly.

A UUID is a 128 bit value that any process can generate without asking a central counter. RFC 9562, published in May 2024, defines version 4 with 122 random bits and version 7, which leads with a 48 bit Unix timestamp in milliseconds so that keys sort by creation time. The RFC notes that time-ordered UUIDs benefit from greater database index locality. UUIDs fit operational databases and event ids, where many writers insert at once. In a warehouse they're as wide as a hash without being repeatable.

Choose by how the table is loaded. A dimension that 1 job maintains incrementally can use a sequence. A model that is rebuilt from source on each run needs a hash, because a rebuilt sequence renumbers every row. A table written by many services at once needs a UUID or a hash.

Sequence vs hash vs UUID surrogate keys

Sequence or identity
  • Width8 bytes as BIGINT
  • Same input, same keyNo
  • Fact load needs a lookupYes
  • Parallel writersNeed coordination
  • Collision riskNone
Hash of natural key
  • Width16 bytes, 32 as hex
  • Same input, same keyYes
  • Fact load needs a lookupOnly for type 2
  • Parallel writersSafe
  • Collision riskNegligible at 128 bits
UUID
  • Width16 bytes
  • Same input, same keyNo
  • Fact load needs a lookupYes
  • Parallel writersSafe
  • Collision riskNegligible

Can hash surrogate keys collide?

2 different natural keys can hash to the same value, and how likely that is depends almost entirely on the width of the hash. The birthday bound gives the estimate: with n keys and a hash of b bits, the chance of at least 1 collision is about n squared divided by 2 to the power of b plus 1. For a 128 bit hash such as MD5 over 1 billion keys, that is roughly 1 in 680 quintillion. No warehouse will see it.

A narrower hash collides far more often. A 64 bit hash over the same 1 billion keys collides with a probability of 2.7%, and at 4 billion keys it reaches 39%. Snowflake's documentation for its 64 bit HASH function says the same thing in words: don't use it to create unique keys, because around 4 billion rows it is reasonably likely to return a duplicate. BigQuery's FARM_FINGERPRINT is also 64 bits. A 32 bit hash is worse again: 100,000 keys collide with a probability of 69%. Never truncate a hash to make the key shorter.

The collisions teams meet in practice come from how the input string is built. Concatenate 2 columns with no separator and ('ab', 'c') and ('a', 'bc') both become abc. A separator fixes that case and not every case, because ('x-y', 'z') and ('x', 'y-z') both become x-y-z when the separator is -. A NULL that is coalesced to an empty string becomes equal to a real empty string. And the same key cast to a string in 2 ways, 1 in 1 model and 1.0 in another, yields 2 different hashes for 1 thing, which shows up as fact rows that match no dimension row.

MD5 is broken for security purposes, where an attacker crafts 2 inputs to collide on purpose. Customer ids are not adversarial, so that weakness does not apply to key generation. A uniqueness check on the key column catches every case here, and it costs 1 query per load.

Surrogate key SQL: assign it, hash it, look it up

SQLdim_customer.sql
CREATE TABLE dim_customer (
    customer_key  BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer_id   TEXT        NOT NULL,
    city          TEXT        NOT NULL,
    valid_from    TIMESTAMPTZ NOT NULL,
    valid_to      TIMESTAMPTZ,
    is_current    BOOLEAN     NOT NULL,
    UNIQUE (customer_id, valid_from)
);

Unknown, missing and late-arriving rows

Some fact rows arrive with no usable natural key: a guest checkout with no customer, a sale with a product code the catalog has never seen. Storing NULL in the foreign key is the tempting answer and a costly one. An inner join to the dimension drops those rows without an error, and the revenue they carry disappears from every report that joins to customer.

A surrogate key solves this with a row the business never had. The dimension gets a member with a reserved key, commonly -1, whose attributes read Unknown, and the fact load writes -1 whenever the lookup finds nothing. Kimball made the same argument in 1998: a null key sets off the referential integrity alarm, so the warehouse needs keys of its own for the cases production can't describe. A natural key can't do this, because the reserved value would have to be invented inside someone else's key space.

The same idea handles a fact that arrives before its dimension row. When an order references a customer the dimension doesn't hold yet, the load inserts a placeholder row with the natural key, a new surrogate key and Unknown attributes, and points the fact at it. When the customer record lands, the load overwrites the placeholder's attributes in place. The fact row never needs an update, because the key it stored was right from the start.

Surrogate keys in PostgreSQL, Snowflake, BigQuery and Databricks

Every platform can generate the key. Few of them enforce it, and that changes what the pipeline has to check.

PostgreSQL declares an identity column with GENERATED ALWAYS AS IDENTITY or GENERATED BY DEFAULT AS IDENTITY. The PostgreSQL documentation on identity columns is explicit that an identity column doesn't guarantee uniqueness, since the sequence can be reset or a value inserted by hand, so the column still needs a PRIMARY KEY or UNIQUE constraint. With that constraint in place, PostgreSQL enforces it on every write.

Snowflake offers AUTOINCREMENT and IDENTITY, both starting at 1 with a step of 1 by default, and its documentation states that sequence numbers aren't guaranteed to be free of gaps. On standard tables Snowflake does not enforce PRIMARY KEY or UNIQUE constraints, and it doesn't enforce FOREIGN KEY either. Only hybrid tables enforce them.

BigQuery accepts primary and foreign key declarations and doesn't enforce them. Its documentation says the user is responsible for keeping the data consistent with them, and the optimizer uses them to remove or reorder joins. Databricks identity columns must be BIGINT, produce values that are unique but not guaranteed to be contiguous, and disable concurrent transactions on the Delta table that declares one. On Databricks, primary key and foreign key constraints are informational only, and so are unique constraints.

On 3 of these 4 platforms nothing stops a duplicate key from landing. Uniqueness becomes a check the pipeline runs after each load: the surrogate key is unique and not null, the natural key plus the version start is unique, and every fact key finds a dimension row.

When a natural key is enough

Some tables do not need a surrogate key. Kimball's own guidance exempts the date dimension: it's highly predictable and stable, so it can use a more meaningful primary key, and an integer in year, month, day order lets a person read a partition filter at a glance.

Staging and raw tables keep the source's keys, because their job is to mirror the source and a second identifier would only have to be explained. A fact table is identified by its grain. The Kimball Group calls a single-column fact surrogate key useful but not required, and the order number on an order line stays in the fact row as a degenerate dimension without a dimension table behind it.

Small reference dimensions whose codes are public and standardized, such as currency or country codes, are the judgment call. A natural key there saves a join in most queries. The price is a harder migration on the day the dimension needs history or a second source. If neither is plausible, the natural key is the simpler model.

Data Vault takes the opposite position for hubs: the key is a hash of the business key, so that hubs can load in parallel with links and satellites, with no lookups between them. That design is covered in the guide to Data Vault modeling.

Surrogate key mistakes that corrupt a model

Dropping the natural key is the most damaging mistake. Without it a load cannot tell whether an incoming customer already has a row, so it inserts a second one, and the surrogate key makes the duplicate look legitimate. The natural key stays on the row, with a uniqueness check, for the life of the table.

Regenerating sequence keys corrupts a model without raising an error. A dimension built with ROW_NUMBER() on each full refresh renumbers its rows whenever the input order shifts, and every fact row loaded earlier now points at a different customer. Either persist the dimension and add to it, or use a hash.

Hashing columns that change breaks the key. A key built from customer_id and email changes when the email does, and the old facts are orphaned. Hash only what identifies the row: the natural key, plus the version start in a type 2 dimension.

Reading meaning into the number causes errors that are hard to spot. A higher sequence value doesn't prove a later event, since failed inserts leave gaps and concurrent writers interleave, so order by a timestamp. Sequential keys in a URL or an export also reveal how many customers or orders exist. Keep surrogate keys inside the warehouse and show business users the natural key.

Surrogate keys in data engineering interviews

Surrogate keys rarely get a question of their own. They come up inside a modeling prompt, at the moment an interviewer asks what the primary key of a dimension is and why. A strong answer names the natural key, says what would make it change or repeat, and then chooses the key type from how the table is loaded.

The follow-ups are predictable. How does a fact row find the right version of a customer who has moved? What does the load do when the customer is missing? What happens to the keys when the dimension is rebuilt? Each one is answered by a mechanism from this guide. The version lookup answers the first and the unknown member answers the second. The third comes down to the choice between a sequence and a hash. Questions about tracking change usually continue into the ground the slowly changing dimension interview questions cover.

The data modeling interview questions show how these prompts are worded, and the data modeling practice problems let you design the tables and keys yourself. For how the whole round runs, from requirements to grain to keys, see the guide to the data modeling interview round.

Surrogate key FAQ

What is a surrogate key in simple terms?+
A surrogate key is an identifier the database or warehouse generates for a row. It has no business meaning and exists only so other tables can point at that row. An auto-incrementing integer id is the most familiar example.
What is the difference between a surrogate key and a natural key?+
A natural key comes from the data itself and means something to the business, such as a customer number or an email address for a customer and a SKU for a product. A surrogate key is generated by the system and means nothing. The natural key says which real-world thing a row describes, and the surrogate key says which row it is.
Is a surrogate key the same as a primary key?+
No. Primary key is a role: the column or columns a table declares as its unique row identifier. Surrogate key is a kind of value: one generated by the system. A surrogate key is usually used as the primary key, but a natural key can fill that role too.
Is a business key the same as a natural key?+
In practice, yes. Business key and natural key both name the identifier the source system or the business already uses for a thing, and operational key is another name for it. Data Vault writing prefers business key and Kimball's dimensional modeling prefers natural key.
What is an example of a surrogate key?+
A customer the CRM calls C-1042 is stored in dim_customer with customer_key 7. C-1042 is the natural key. The 7 is the surrogate key: the warehouse assigned it, it says nothing about the customer, and fact tables join on it.
Should a surrogate key be an integer, a hash or a UUID?+
An integer from a sequence or identity column is the narrowest key, so use it when 1 process loads the table and the keys are persisted. When tables are rebuilt or loaded in parallel and the key must come out the same every time, use a hash of the natural key. A UUID fits when many writers create rows without coordinating, which is more common in applications than in warehouses.
Do fact tables need a surrogate key?+
Not usually. A fact row is identified by its grain, often the combination of its dimension keys or a source transaction id. The Kimball Group describes a single-column fact surrogate key as useful but not required, for instance to resume an interrupted load or to turn an update into a delete and an insert.
Can a surrogate key change?+
It should not. A sequence key changes only if the table is rebuilt and the numbers are handed out again in a different order, which silently breaks every fact row that stored the old value. A hash key changes if any column it hashes changes, so hash only columns that identify the row.
02 / Why practice

The candidate who gets the offer

  1. 01

    Reading a solution is not the same as writing one

    Every engineer who has frozen on a query they had read a dozen times knows the gap. The only preparation that closes it is producing the answer yourself, under time, before the interview does it for you

  2. 02

    76% of hiring managers reject on the coding task, not the resume

    From HackerRank's 2024 Developer Skills Report. Candidates who look strong on paper still fail the live screen if they haven't done timed, executable practice

  3. 03

    The round is won on tradeoffs, not on the diagram

    Grain, star vs snowflake, SCD type, conformed dimensions, late-arriving data. Modeling under live pushback is what separates the bands, and it is the half almost nobody rehearses

Related guides