Video in progress

How do `serial` and `GENERATED AS IDENTITY` columns differ in PostgreSQL?

Both hand out automatic numbers using a sequence underneath. serial is the old PostgreSQL-specific shorthand; IDENTITY is the SQL standard and causes fewer problems with permissions and sequence management. IDENTITY is recommended for new tables.

📖 Answer

-- the old way
CREATE TABLE a (id bigserial PRIMARY KEY);

-- PostgreSQL 10+
CREATE TABLE b (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY);

serial is really a macro for "create a sequence + put DEFAULT nextval(...) on the column". That's why some odd cases show up later: when you hand the table to another user, the sequence needs a separate grant, CREATE TABLE ... (LIKE a) ends up sharing the sequence, and so on.

GENERATED ALWAYS forbids supplying id by hand (use OVERRIDING SYSTEM VALUE if you must). BY DEFAULT allows it, which is handy when importing data.

What you should know about both: the numbers are not gapless. If a transaction rolls back, the value it took isn't returned. So don't use id as an invoice number; if "1, 2, 4" comes out, accounting will ask questions.

In JPA, @GeneratedValue(strategy = IDENTITY) disables batch inserts; with the SEQUENCE strategy and an allocationSize, you let Hibernate batch them.