Sub topic 4
Creating an identity column
This chapter assumes you can write basic CREATE TABLE, INSERT and SELECT statements. It also assumes you know what a primary key is and the ranges of smallint, integer and bigint. You should have a rough idea of what commit and rollback do. The chapter needs PostgreSQL 10 or later, the first version with identity columns.
What an identity column is
An identity column is a column whose value PostgreSQL fills in automatically from a counter when you insert a row without supplying that value. It is the SQL-standard way to get auto-incrementing IDs. It replaces the older serial pseudo-type, which earlier chapters covered.
The general syntax is:
column_name data_type GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( sequence_options ) ]The next chapter compares ALWAYS with BY DEFAULT in depth. Here we use ALWAYS and focus on what the declaration creates and how to inspect it.
A first identity column
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL
);
INSERT INTO orders (customer) VALUES ('Ada') RETURNING id;The INSERT names only customer. PostgreSQL computes id and RETURNING id sends it back to you. On a fresh table the first value is 1.
Three separate things are declared in the id line:
- The type,
bigint, which sets the range of possible IDs. - The identity property,
GENERATED ALWAYS AS IDENTITY, which supplies values. - The constraint
PRIMARY KEY, which enforces uniqueness.
The identity property does not make values unique. It only produces numbers. If you leave out PRIMARY KEY or a UNIQUE constraint, nothing stops duplicate IDs from appearing later, for example when someone inserts explicit values.
What PostgreSQL creates behind the scenes
Declaring an identity column creates an internal sequence. A sequence is a database object that hands out the next number in a series each time it is asked. PostgreSQL names it <table>_<column>_seq, so here it is orders_id_seq.
The identity column's sequence differs from one you create yourself with CREATE SEQUENCE:
- The column owns it. If you drop the table or the column, the sequence goes too.
- You cannot drop it on its own with
DROP SEQUENCE. You remove it by dropping the identity property from the column. - Its data type follows the column type, so a
smallintcolumn gets asmallintsequence with a matching maximum.
Each insert calls nextval on the sequence for you. The default for the column is not an ordinary DEFAULT expression. In fact you cannot add a separate DEFAULT to an identity column. PostgreSQL rejects the combination, because the identity property already defines how values are produced.
Identity implies NOT NULL
An identity column is automatically NOT NULL. You do not need to write it, though writing it does no harm. Explicitly inserting NULL fails. Inserting a row without mentioning the column works, because the generator supplies the value.
Inspecting an identity column
You can confirm how a column was declared through the standard information_schema views:
SELECT column_name, is_identity, identity_generation,
identity_start, identity_increment
FROM information_schema.columns
WHERE table_name = 'orders' AND column_name = 'id';For orders, is_identity is YES, identity_generation is ALWAYS, and the start and increment are both 1. The identity_minimum, identity_maximum and identity_cycle columns of the same view describe the other limits.
To find the sequence's name, use pg_get_serial_sequence. It works for identity columns as well as for serial columns:
SELECT pg_get_serial_sequence('orders', 'id');This returns public.orders_id_seq. You can then pass that name to functions such as setval, which a later chapter uses.
The psql command \d orders also shows the column with generated always as identity in its Default column.
Choosing the column type
The identity property works on integer columns: smallint, integer and bigint. The type controls how many IDs you can ever generate.
| Type | Maximum value | Typical use |
|---|---|---|
| `smallint` | 32,767 | Tiny lookup tables |
| `integer` | 2,147,483,647 | Tables that will never get near two billion rows or inserts |
| `bigint` | 9,223,372,036,854,775,807 | Default choice for tables that grow |
When the sequence reaches its maximum, the next insert fails with an error that the sequence reached its maximum value. The sequence does not wrap around, unless you declared CYCLE, which would then produce duplicates. A later chapter covers overflow in depth. For now, prefer bigint for any table that could grow large. It costs 4 extra bytes per row and per index entry compared with integer, and changing the type of a populated column later requires a table rewrite.
Sequence options in the declaration
You can tune the underlying sequence by putting options in parentheses after AS IDENTITY. The options are the same ones CREATE SEQUENCE accepts: START WITH, INCREMENT BY, MINVALUE, MAXVALUE, CACHE and CYCLE.
CREATE TABLE tickets (
id integer GENERATED BY DEFAULT AS IDENTITY (START WITH 1000 INCREMENT BY 10) PRIMARY KEY,
title text NOT NULL
);
INSERT INTO tickets (title) VALUES ('first'), ('second') RETURNING id;The two returned IDs are 1000 and 1010. A multi-row INSERT pulls one sequence value per row, in order.
This example uses BY DEFAULT, which accepts explicit values as well. The next chapter explains the difference. The sequence options work the same way with either mode.
A later chapter covers the options in detail. Two points matter now:
- Options sit inside the parentheses after
IDENTITY, not after the column type. - The defaults are start
1, increment1, minimum1, maximum equal to the largest value of the column type,CACHE 1, andNO CYCLE.
Rules and restrictions
- A table can have only one identity column. Declaring a second one raises an error.
- An identity column cannot also have a
DEFAULTclause. - The column type must be
smallint,integerorbigint(or a domain over one of them). Declaring identity ontextoruuidfails. - The property can also be added to an existing column with
ALTER TABLE, if the column is alreadyNOT NULLand has no default. A later chapter shows this.
A complete example you can run
This script creates the table, inserts three rows, and shows the generated IDs:
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
price numeric(10, 2) NOT NULL
);
INSERT INTO products (name, price)
VALUES ('Pen', 1.50), ('Notebook', 4.20), ('Stapler', 8.00)
RETURNING id, name;
SELECT id, name FROM products ORDER BY id;The RETURNING clause gives back 1, 2 and 3 along with the names. The SELECT afterwards returns the same three rows.
Common errors
- Writing
id bigint GENERATED ALWAYS AS IDENTITYand expecting uniqueness. AddPRIMARY KEYorUNIQUE. - Putting the options before
AS IDENTITY. They go in parentheses after it. - Using a non-integer type, such as
text, for an identity column. - Trying to insert your own
idinto aGENERATED ALWAYScolumn. That raisescannot insert a non-DEFAULT value into column "id". The next chapter shows how to handle it. - Trying to drop the backing sequence with
DROP SEQUENCE. UseALTER TABLE ... ALTER COLUMN ... DROP IDENTITYinstead.
Exercise
You run CREATE TABLE invoices (id integer GENERATED ALWAYS AS IDENTITY, total numeric NOT NULL); and then insert two rows without an id. Later a script inserts a third row using OVERRIDING SYSTEM VALUE with id = 1. Can the duplicate happen, and what name does PostgreSQL give the sequence behind the column?
Show answer
Yes, the duplicate can happen, because the identity property only generates numbers and the table has no PRIMARY KEY or UNIQUE constraint on id. OVERRIDING SYSTEM VALUE lets the script insert an explicit value. The backing sequence is named invoicesidseq. Adding PRIMARY KEY (or UNIQUE) to the id column would make the third insert fail.
Exercise
Write a table definition for a log table named events with a bigint identity column called id that starts at 500 and increases by 5, accepts explicit values when supplied, and is the primary key. What are the first two IDs generated by two inserts that omit id?
Show answer
CREATE TABLE events (id bigint GENERATED BY DEFAULT AS IDENTITY (START WITH 500 INCREMENT BY 5) PRIMARY KEY, message text NOT NULL); The first two generated IDs are 500 and 505.