Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

Compare SERIAL, IDENTITY columns (GENERATED ALWAYS / BY DEFAULT AS IDENTITY) and explicit sequences in PostgreSQL. Why does Hibernate batch inserts with SEQUENCE but not with IDENTITY generation?

SERIAL is an old PostgreSQL shorthand that creates a separate sequence and a column default; an IDENTITY column is the SQL standard form, where the sequence belongs to the column and follows its permissions. GENERATED ALWAYS refuses values we supply unless we write OVERRIDING SYSTEM VALUE, while BY DEFAULT accepts them. Hibernate can batch inserts with SEQUENCE because it fetches ids before the insert, but with IDENTITY it must run every insert at once to learn the id the database generated.

Why this question is asked

Every table needs a primary key, and most Java teams let the database hand out numbers for it. The choice between SERIAL, an IDENTITY column and an explicit sequence looks like a detail, yet it decides who may insert rows, whether a migration script can load old ids, and how fast Hibernate can save ten thousand entities in one go. Interviewers ask it because it connects SQL, JPA mapping and performance in one question. In this answer, we will recap what a sequence is, compare the three ways of using one in PostgreSQL, see the difference between ALWAYS and BY DEFAULT, and then follow Hibernate through a batch of inserts with each generation strategy, including what allocationSize does and why ids always have gaps.

1A Quick Recap of Sequences

A sequence is a small database object whose only job is to hand out the next number. We call nextval('order_seq') and it returns 1, then 2, then 3, safely even when many sessions ask at the same moment. It can also step by more than one: with INCREMENT BY 50, the calls return 1, 51, 101 and so on.

A sequence on its own is not attached to any table. We have to connect it to a column somehow, and PostgreSQL offers three ways to do that: the SERIAL pseudo type, an IDENTITY column, or a sequence we create ourselves and call from a default or from the application.

2SERIAL, IDENTITY and Explicit Sequences Side by Side

SERIAL is not a real type. When we write id serial, PostgreSQL quietly creates a sequence named orders_id_seq, makes the column an integer with DEFAULT nextval('orders_id_seq'), marks it NOT NULL and records that the sequence is owned by the column, so dropping the column drops the sequence. It works, but the sequence is a separate object with its own permissions, so a role granted INSERT on the table also needs USAGE on the sequence, and tools that copy table definitions can lose the link.

An IDENTITY column says the same thing in the SQL standard way. The sequence still exists, but it is internal to the column: permissions on the table are enough, ALTER TABLE changes its options, and the intent is visible in the table definition.

SQL
CREATE TABLE orders_old (id serial PRIMARY KEY, total numeric); -- sequence orders_old_id_seq + DEFAULT
CREATE TABLE orders (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, total numeric);
CREATE TABLE imports (id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, total numeric);
INSERT INTO orders (total) VALUES (10); -- id 1, generated
INSERT INTO orders (id, total) VALUES (500, 10); -- ERROR: cannot insert a non-DEFAULT value into column "id"
INSERT INTO orders (id, total) OVERRIDING SYSTEM VALUE VALUES (500, 10); -- allowed, id 500
INSERT INTO imports (id, total) VALUES (500, 10); -- allowed, BY DEFAULT accepts our value
Three ways to number rows in PostgreSQL
FormSequenceExplicit idsGood for
serial / bigserialseparate object, needs its own grantsacceptedold schemas
IDENTITY ALWAYSinternal to the columnonly with OVERRIDING SYSTEM VALUEnew tables, strict
IDENTITY BY DEFAULTinternal to the columnacceptedtables that load old ids
CREATE SEQUENCEexplicit, shared if we wantthe caller decidesHibernate pooled ids
IDENTITY is the standard replacement for SERIAL; an explicit sequence lets the application fetch ids ahead of time.

Notice the difference between the two IDENTITY forms. GENERATED ALWAYS protects the column: nobody can slip in their own id by accident, and a deliberate data load must say OVERRIDING SYSTEM VALUE. GENERATED BY DEFAULT behaves like SERIAL and accepts any value we give. There is a catch with both: if we insert explicit ids, the sequence does not know about them, so after a load we must move it forward with ALTER TABLE ... ALTER COLUMN id RESTART WITH or setval(), or the next generated id collides with a loaded one.

An explicit sequence, created with CREATE SEQUENCE, is the right choice when the application, not the column, should ask for numbers, or when several tables share one numbering. This is the form Hibernate likes best, as we will see.

3Why IDENTITY Stops Hibernate From Batching

JDBC batching means sending many INSERT statements to the database in one network round trip instead of one by one. With hibernate.jdbc.batch_size=50, Hibernate collects inserts and sends them fifty at a time, which can make a bulk save several times faster.

But Hibernate has a rule: when we call persist(), the entity must have its id right away, because the persistence context, the map of managed entities Hibernate keeps for the transaction, is keyed by id. With GenerationType.IDENTITY the id does not exist until the row is inserted. So Hibernate has no choice: it executes the INSERT immediately, reads the generated key back, and moves on. Each entity becomes its own round trip, and batching is switched off for those inserts.

Java
@Entity
class Order {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
}
for (int i = 0; i < 1000; i++) em.persist(new Order()); // 1000 INSERT round trips, no batching
@Entity
class Invoice {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "inv")
@SequenceGenerator(name = "inv", sequenceName = "invoice_seq", allocationSize = 50)
Long id;
}
// CREATE SEQUENCE invoice_seq INCREMENT BY 50;
for (int i = 0; i < 1000; i++) em.persist(new Invoice()); // 20 nextval calls + 20 batches of 50 inserts
Step throughSaving entities with SEQUENCE and allocationSize 50
ServiceHibernatePostgreSQL
persist(invoice) x 50
select nextval('invoice_seq')
101, so ids 52..101 are ours
assign ids from memory
commit
one batch of 50 INSERTs
50 rows inserted

7 messages in order. Play them, or step through them one at a time.

With IDENTITY, each persist would instead send its own INSERT and wait for the generated key.

With SEQUENCE, Hibernate asks the sequence for an id before the insert, so persist() can return at once and the INSERT can wait in the batch until flush. The pooled optimizer makes this even cheaper. Because the sequence steps by 50, one nextval call that returns 101 tells Hibernate that the block 52 to 101 is reserved for it, and it hands out those fifty ids from memory. A thousand entities cost twenty sequence calls instead of a thousand.

The rule is that allocationSize must match the sequence's INCREMENT BY. If the sequence steps by 1 while Hibernate believes it steps by 50, two application instances compute overlapping blocks and eventually fail with duplicate key errors.

4Why Ids Always Have Gaps

Sequences are deliberately not transactional. When a transaction calls nextval and then rolls back, the number is not returned to the sequence, because handing it back would force every other session to wait and see whether we commit. PostgreSQL also caches sequence values per session when CACHE is set, and those are lost when the session ends or the server crashes. The pooled optimizer adds its own gaps: when an application restarts, the unused part of its block of fifty is simply skipped.

So ids from SERIAL, IDENTITY or a sequence are unique and roughly increasing, and nothing more. We must never use them as gapless numbers such as invoice numbers, and we should not read meaning into a jump from 1050 to 1101.

5Follow-up questions

What happens if allocationSize does not match the sequence increment?

Hibernate computes its block of ids from the value nextval returns, assuming the sequence moved by allocationSize. If the sequence really moved by 1, two instances get values 100 and 101 and both believe they own about fifty ids below their value, so the ranges overlap and inserts fail with duplicate keys. Recent Hibernate versions check the increment at startup and throw by default; the behaviour is controlled by hibernate.id.sequence.increment_size_mismatch_strategy (check your version for the exact options).

Should new PostgreSQL tables use SERIAL?

No. IDENTITY does the same job in the standard way with cleaner permissions and ownership. If we use Hibernate and care about batch inserts, we can still use an IDENTITY column for other clients and map the entity to an explicit sequence, but it is simpler to choose one approach per table.

Does GenerationType.AUTO give us batching?

With Hibernate 6 and later on PostgreSQL, AUTO for a numeric id maps to a sequence, by default with an allocation size of 50, so batching works. It is still better to state the strategy and sequence name explicitly so the mapping matches the migration script.

6Conclusion

In this answer, we saw that SERIAL is a legacy shortcut that creates a loose sequence and a default, while IDENTITY ties the sequence to the column, with ALWAYS rejecting our own values unless we say OVERRIDING SYSTEM VALUE and BY DEFAULT accepting them. Hibernate cannot batch IDENTITY inserts because it must run each one to learn its id, but with a sequence and a pooled optimizer whose allocationSize matches INCREMENT BY, it reserves ids in blocks and sends inserts in batches. And because sequences ignore rollbacks, every generated id can have gaps.

What to say in the interviewAbout 80 seconds aloud

Open with

SERIAL is the old PostgreSQL shorthand: it creates a separate sequence, sets a nextval default and makes the sequence owned by the column, but the sequence keeps its own permissions, so inserting roles need USAGE on it as well.

Then, if they want more

IDENTITY is the SQL standard way. The sequence is internal to the column, table permissions are enough, and the definition shows the intent.

GENERATED ALWAYS rejects an explicit id unless the insert says OVERRIDING SYSTEM VALUE, which protects the column; BY DEFAULT accepts our values, which suits tables that load old ids, though then we must move the sequence forward afterwards. For Hibernate the big difference is batching. Hibernate needs the id at persist time.

With IDENTITY the id only exists after the insert, so Hibernate runs each insert immediately and JDBC batching is lost. With a sequence it calls nextval first, and with the pooled optimizer and allocationSize 50, matching INCREMENT BY 50 on the sequence, one call reserves fifty ids, so a thousand inserts become twenty sequence calls and twenty batches.

If the two numbers disagree, instances can hand out overlapping ids. Finally, sequences are not transactional, so rollbacks, caches and restarts leave gaps, and I never treat these ids as gapless business numbers.

About this answer

Last updated
12 November 2026
Versions it names
Hibernate 6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Compare SERIAL, IDENTITY columns (GENERATED ALWAYS / BY DEFAULT AS IDENTITY) and...": https://scrivio-interview-library.netlify.app/databases/stored-code/c3b9f06569/