Sub topic 7
Generating Key Values Automatically
This chapter assumes you can write INSERT, SELECT and basic CREATE TABLE statements. You should also know what a primary key is. Here you will learn how a database can produce key values for you, how the standard identity syntax works, and where the common systems differ.
Why generate keys
A primary key must be unique and never null. Many tables have no natural value that fits, such as an order number or a customer id. If application code picks the next number, two sessions can pick the same one. A database-generated value avoids that race, because the database hands out each number once.
An identity column is a column whose value the database fills in when you insert a row. It is usually an integer, and it usually serves as the primary key.
The standard identity syntax
The SQL standard defines identity columns. PostgreSQL (version 10 and later) and Oracle (12c and later) support this syntax.
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);The column has three parts:
INTEGERis the data type. An identity column must have a numeric type.GENERATED ALWAYS AS IDENTITYtells the database to supply the value.PRIMARY KEYmakes the column the row identifier.
An identity column is not automatically unique. It is also not automatically a primary key. The PRIMARY KEY clause is what adds those guarantees. Identity columns are implicitly NOT NULL.
Insert rows without naming the key column:
INSERT INTO customers (email, full_name)
VALUES ('[email protected]', 'Ada Lovelace'),
('[email protected]', 'Alan Turing');
SELECT customer_id, full_name FROM customers ORDER BY customer_id;On a new table, this returns 1, Ada Lovelace and 2, Alan Turing.
ALWAYS versus BY DEFAULT
There are two forms, and they differ in what happens when you supply your own value.
| Form | Explicit value in `INSERT` | Typical use |
|---|---|---|
| `GENERATED ALWAYS AS IDENTITY` | Rejected unless you override it | Keys that only the database should assign |
| `GENERATED BY DEFAULT AS IDENTITY` | Accepted, and the generator is used when you omit the column | Data loads and migrations that must keep old ids |
With ALWAYS, this statement fails in PostgreSQL:
INSERT INTO customers (customer_id, email, full_name)
VALUES (500, '[email protected]', 'Grace Hopper');PostgreSQL reports an error that says you can only insert DEFAULT into the identity column. To load a known id on purpose, add an override clause:
INSERT INTO customers (customer_id, email, full_name)
OVERRIDING SYSTEM VALUE
VALUES (500, '[email protected]', 'Grace Hopper');Choose ALWAYS by default. It stops application code from accidentally writing keys that clash with the generator.
The generator does not know about your explicit values
The generator is a counter kept separately from the table's rows. If you insert id 500 by hand, the counter does not move. Later, when the counter reaches 500, the generated value collides with the existing row and the insert fails with a primary key violation.
This is the most common identity bug. It appears after a data import into a BY DEFAULT column. After such an import, move the counter past the largest existing value. In PostgreSQL:
ALTER TABLE customers
ALTER COLUMN customer_id RESTART WITH 501;Set the number to one more than the current maximum. Do not copy 501 blindly. Check the real maximum first with SELECT MAX(customer_id) FROM customers.
Gaps are normal
Generated numbers are not guaranteed to be consecutive. The counter advances even when the work is undone:
- A failed insert, for example one that violates a
UNIQUErule, still consumes a number. - A rolled-back transaction does not return its numbers.
- Deleting a row does not free its number for reuse.
Generators work this way so that concurrent sessions never wait for each other to commit. Treat the key as an identifier only. Do not use it as a count of rows or as a gap-free invoice number. If the law or your business requires gap-free numbering, you need a separate, carefully controlled process.
Getting the generated value back
After an insert you often need the new key, for example to insert child rows. Do not run SELECT MAX(id), because another session may have inserted a row in between. Ask the insert statement to return it. PostgreSQL has RETURNING:
INSERT INTO customers (email, full_name)
VALUES ('[email protected]', 'Edsger Dijkstra')
RETURNING customer_id;Other systems use different tools, listed in the next section.
Dialect differences
Identity syntax is the area where systems differ most.
| System | Syntax for an auto-generated key | Get the new value |
|---|---|---|
| PostgreSQL | `GENERATED ALWAYS AS IDENTITY` (also the older `SERIAL` shorthand) | `RETURNING` |
| MySQL, MariaDB | `AUTO_INCREMENT` | `LAST_INSERT_ID()` |
| SQL Server | `IDENTITY(1,1)` | `SCOPE_IDENTITY()` or `OUTPUT` |
| Oracle 12c and later | `GENERATED ... AS IDENTITY` | `RETURNING ... INTO` |
| SQLite | `INTEGER PRIMARY KEY` (optionally `AUTOINCREMENT`) | `last_insert_rowid()` |
Here is the same table in MySQL and in SQL Server:
-- MySQL
CREATE TABLE customers (
customer_id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL
);
-- SQL Server
CREATE TABLE customers (
customer_id INT IDENTITY(1,1) PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL
);In SQL Server, IDENTITY(1,1) means "start at 1, step by 1". The standard form also accepts options such as START WITH and INCREMENT BY in parentheses after IDENTITY.
CREATE TABLE tickets (
ticket_id INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1000 INCREMENT BY 1) PRIMARY KEY,
title VARCHAR(200) NOT NULL
);The SERIAL type in older PostgreSQL code creates a separate sequence object and sets a default on the column. It still works, but a SERIAL column does not block explicit values. Prefer the identity form in new code.
Choosing the integer size
An INTEGER column holds values up to about 2.1 billion. A busy table that inserts millions of rows a day, and consumes numbers on failed inserts, can reach that ceiling. When it does, inserts fail. Changing the type later means rewriting a large table and every foreign key that points to it. For tables that may grow large, use BIGINT from the start:
CREATE TABLE events (
event_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
occurred_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
payload VARCHAR(1000) NOT NULL
);A foreign key column must have a compatible type with the key it references. If events.event_id is BIGINT, then a child table's reference column should be BIGINT too.
When not to use an identity column
- When the table already has a stable natural key, such as a country code, you can use that as the primary key.
- When ids are created in several databases and merged later, sequential numbers will collide. A UUID column is a common alternative.
- Do not expose sequential ids in public URLs if guessing the next one reveals information, such as how many orders you have received.
Common errors
- Inserting a value into a
GENERATED ALWAYScolumn without an override. - Importing rows with explicit ids into a
BY DEFAULTcolumn and not moving the counter, which causes duplicate key errors later. - Expecting no gaps.
- Reading the new id with
MAX(id)instead ofRETURNINGor the system's equivalent. - Choosing
INTEGERfor a table that will outgrow it.
Exercise
A table has item_id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY. You load 1,000 rows with explicit ids 1 to 1000. Two days later, ordinary inserts that omit item_id begin failing with a primary key violation. Why does this happen, and what do you do?
Show answer
The generator is separate from the rows and did not advance when you supplied explicit ids. It starts at 1 and produces values that already exist. Check the maximum with SELECT MAX(itemid) FROM items, then restart the generator above it, for example ALTER TABLE items ALTER COLUMN itemid RESTART WITH 1001 in PostgreSQL. For tables where only the database should assign ids, use GENERATED ALWAYS to prevent the problem.
Exercise
Your invoices table uses an identity column, and finance notices that invoice numbers 7 and 8 are missing. Is this a bug in the database? What should you do if invoice numbers must have no gaps?
Show answer
It is not a bug. Identity values are consumed by rolled-back transactions and failed inserts and are never reused, so gaps are expected. If the numbering must be gap-free, do not rely on the identity value as the invoice number. Use the identity column as the internal key, and assign the visible invoice number in a separate, serialized step.