Sub topic 7
Generating Key Values Automatically
Prerequisites and the core idea
Assume you know how to create tables and insert rows, and that a primary key identifies each row uniquely.
An automatically generated key lets the database choose a new identifier when you insert a row. This avoids making application code calculate the next value. The generated column is usually an integer primary key.
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL
);
INSERT INTO customers (email, full_name)
VALUES ('[email protected]', 'Ada Lovelace');
SELECT customer_id, email, full_name
FROM customers;The customer_id value is generated because the INSERT statement omits that column. The database assigns a value such as 1. The PRIMARY KEY constraint is a separate rule. It prevents duplicate or null identifiers. Identity generation supplies values, while the primary key defines what those values mean.
ALWAYS versus BY DEFAULT
GENERATED ALWAYS AS IDENTITY tells the database to generate the value and reject an explicit value in normal inserts. This protects the column from accidental manual changes.
GENERATED BY DEFAULT AS IDENTITY also generates a value when one is omitted, but it permits an explicitly supplied value. This can help when importing old data.
CREATE TABLE events (
event_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
event_name VARCHAR(100) NOT NULL
);
INSERT INTO events (event_name)
VALUES ('login');
-- Usually rejected because event_id is GENERATED ALWAYS.
INSERT INTO events (event_id, event_name)
VALUES (100, 'imported login');An identity mechanism typically uses an internal sequence or equivalent counter. Values are allocated as inserts occur, so gaps are normal. A failed transaction, a deleted row, or a rolled-back insert can consume a value. Do not treat an identity column as a row count or as a gap-free business number.
Database-system differences
The exact syntax depends on the database system.
| Database system | Common automatic-key syntax | Important detail |
|---|---|---|
| PostgreSQL | `GENERATED ALWAYS AS IDENTITY` | Supports standard identity columns |
| MySQL | `AUTO_INCREMENT` | Usually used with an integer key |
| SQL Server | `IDENTITY(1,1)` | The arguments specify the starting value and increment |
For example, the MySQL form is:
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(255) NOT NULL UNIQUE
);Foreign keys should reference the generated column, not attempt to generate their own matching value. The parent row is inserted first; the child row then stores the parent’s identifier.
Avoid calculating a key with MAX(customer_id) + 1. Concurrent transactions can calculate the same value, causing collisions. Use the database’s identity mechanism or another database-supported key generator.
Exercise
An insert fails after the database generated key value 8. What should you expect for the next successful insert?
Show answer
The next value may be 9 or higher. Identity values are not guaranteed to be gap-free.