Sub topic 5
Generating Key Values
This chapter assumes you know basic CREATE TABLE, INSERT, and data types. It focuses on how a database creates values for surrogate primary keys.
Identity columns
An identity column asks the database to generate a value when an insert does not provide one. In PostgreSQL, GENERATED ALWAYS AS IDENTITY is a common choice:
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL
);
INSERT INTO customers (email, name)
VALUES ('[email protected]', 'Ana');
SELECT customer_id, email, name
FROM customers;The database generates customer_id, while the application supplies the other values. The identity value is unique within this table because it is also the primary key.
GENERATED ALWAYS prevents ordinary inserts from supplying their own identity value. This protects the sequence from accidental collisions. PostgreSQL also supports GENERATED BY DEFAULT AS IDENTITY, which permits an explicitly supplied value when needed, such as during a controlled data migration.
Sequences and generated values
An identity column uses a sequence internally. A sequence is a database object that produces numbers, usually one after another.
CREATE SEQUENCE invoice_number_seq;
CREATE TABLE invoices (
invoice_id INTEGER PRIMARY KEY
DEFAULT nextval('invoice_number_seq'),
issued_on DATE NOT NULL
);Identity columns usually express the design more clearly because the sequence belongs directly to the column. Direct sequences are useful when several tables or processes must draw values from one shared number source.
Generated numbers are not guaranteed to be gap-free. A transaction can consume a number and then roll back. Concurrent transactions can also commit in a different order from the order in which they received numbers. Use a separate business mechanism for legal invoice numbering when every number must be accounted for.
UUID keys
A UUID is a 128-bit value designed to be unique across systems. UUIDs are useful when multiple databases generate rows independently or when exposing sequential IDs would reveal approximate record counts.
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE api_tokens (
token_id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
label VARCHAR(100) NOT NULL
);Numeric identity keys are compact and usually perform well for local relational data. UUIDs simplify distributed generation but require more storage and can make indexes larger. Choose based on where values are generated, not on a preference for a particular format.
| Strategy | Strength | Cost |
|---|---|---|
| Identity integer | Compact and simple | Usually generated by one database |
| Explicit sequence | Flexible shared numbering | More objects to manage |
| UUID | Works across independent systems | Larger indexes and values |
Different database systems use different syntax. MySQL commonly uses AUTO_INCREMENT, SQL Server uses IDENTITY, and Oracle supports identity columns and sequences. Check the target system before moving DDL between databases.
Exercise
Why might a table use UUID keys instead of identity integers?
Show answer
UUIDs allow independent systems to generate keys with a very low collision risk, which helps when data is created across multiple databases.