Sub topic 11
Tuning identity columns: START WITH, INCREMENT BY, CACHE
This chapter assumes you can already create a table with an identity column and know the difference between GENERATED ALWAYS, BY DEFAULT and BY DEFAULT ON NULL. It covers the options in parentheses after AS IDENTITY. These control where the numbers start, how far apart they are, and how many are held in memory.
What an identity column really is
An identity column is backed by a sequence that Oracle creates and manages for you. The sequence has a system-generated name such as ISEQ$$_73512, and the column's default expression calls NEXTVAL on it. The identity options are sequence options. Every behavior below, including gaps, comes from how Oracle sequences work.
You can see the backing sequence in the data dictionary.
SELECT table_name, column_name, generation_type, sequence_name, identity_options
FROM user_tab_identity_cols
WHERE table_name = 'EMPLOYEES';The identity_options column shows the effective settings as text. This includes defaults you never wrote, such as CACHE_SIZE: 20.
The options at a glance
| Option | Default | Effect |
|---|---|---|
| `START WITH n` | 1 for ascending, `MAXVALUE` for descending | First value generated. |
| `INCREMENT BY n` | 1 | Step between values. A negative step counts down. |
| `MAXVALUE n` / `NOMAXVALUE` | 9999999999999999999999999999 | Highest value the generator can produce. |
| `MINVALUE n` / `NOMINVALUE` | 1 | Lowest value the generator can produce. |
| `CYCLE` / `NOCYCLE` | `NOCYCLE` | Whether to wrap around at the limit. |
| `CACHE n` / `NOCACHE` | `CACHE 20` | How many values Oracle preallocates in memory. |
| `ORDER` / `NOORDER` | `NOORDER` | Whether values are guaranteed in request order across Oracle RAC instances. |
You can write the options in any order inside the parentheses. This chapter concentrates on START WITH, INCREMENT BY and CACHE, then touches the limit options.
START WITH and INCREMENT BY
Use START WITH to reserve a range for special rows or to make identifiers look different from other numbering schemes. Use INCREMENT BY when ids must be spaced, for example when several systems share a numbering space or you want room to insert manual rows between generated ones.
CREATE TABLE invoices (
invoice_id NUMBER GENERATED ALWAYS AS IDENTITY
(START WITH 100 INCREMENT BY 10 NOCACHE),
customer VARCHAR2(100) NOT NULL,
amount NUMBER(10,2) NOT NULL,
CONSTRAINT invoices_pk PRIMARY KEY (invoice_id)
);
INSERT INTO invoices (customer, amount) VALUES ('Acme', 250.00);
INSERT INTO invoices (customer, amount) VALUES ('Globex', 90.50);
INSERT INTO invoices (customer, amount) VALUES ('Initech', 12.00);
COMMIT;
SELECT invoice_id, customer FROM invoices ORDER BY invoice_id;The query returns the ids 100, 110 and 120.
A negative INCREMENT BY makes the column count down. In that case set START WITH to the highest value you want first and MINVALUE to a floor you can live with.
CREATE TABLE countdown_tickets (
ticket_no NUMBER GENERATED ALWAYS AS IDENTITY
(START WITH 1000 INCREMENT BY -1 MINVALUE 1 MAXVALUE 1000 NOCACHE),
note VARCHAR2(50)
);START WITH and rows you insert yourself
The generator does not look at the data in the table. If the column is BY DEFAULT or BY DEFAULT ON NULL, you can insert explicit values, and the generator will not skip over them.
In the employees table from earlier chapters, START WITH 1000 combined with a manually inserted 5000 is a trap. The generator will eventually reach 5000, and that insert fails with ORA-00001 on EMPLOYEES_PK. Two ways to avoid it:
- Keep manual ids outside the generator's future range, for example below the
START WITHvalue. - Use
GENERATED ALWAYSso nobody can insert explicit values at all.
CACHE and why gaps appear
A sequence has to record its position somewhere durable. Updating the data dictionary on every NEXTVAL is expensive, so Oracle reads a block of values at once, holds them in the shared pool, and updates the dictionary once per block. With the default CACHE 20, the dictionary is touched once for every 20 ids.
The trade-off:
- A larger cache means fewer dictionary updates, so less contention when many sessions insert at once. It also means more values are lost when the cache is discarded.
NOCACHEwrites to the dictionary on every value. It is slower under concurrency, and it loses fewer values after a restart.CACHE nrequiresnof at least 2. UseNOCACHEto turn caching off.
Cached values disappear when the instance shuts down abnormally, or when the sequence is aged out of the shared pool.
Gaps happen even with NOCACHE
Identity values are not transactional. Once a session takes a value, Oracle does not return it on ROLLBACK, and a failed INSERT still consumes one.
INSERT INTO invoices (customer, amount) VALUES ('Umbrella', 500.00);
ROLLBACK;
INSERT INTO invoices (customer, amount) VALUES ('Hooli', 75.00);
COMMIT;
SELECT invoice_id, customer FROM invoices ORDER BY invoice_id;If the previous maximum was 120, the rolled-back row consumed 130 and Hooli receives 140. Do not use an identity column for a number that must be gapless, such as legal invoice numbers. Use it for what it is good at: unique, ever-increasing technical keys.
Order across RAC instances
With CACHE and Oracle RAC, each instance has its own cache. Instance 1 may hold 100 to 119 while instance 2 holds 120 to 139, so ids are unique but not in time order. ORDER forces request-order allocation across instances at a coordination cost. You rarely need it. Order by a timestamp column instead of relying on key order.
Limits: MAXVALUE, MINVALUE and CYCLE
When the generator reaches MAXVALUE with NOCYCLE, the next insert fails with ORA-08004. A value that fits the sequence but not the column fails with ORA-01438. For example, NUMBER(3) cannot hold 1000.
CYCLE wraps back to MINVALUE. On a primary key this eventually collides with old rows, so it is rarely appropriate there. If you use CYCLE, Oracle requires a CACHE size smaller than the cycle length.
Changing options on an existing column
You can change the options after the table exists. The MODIFY clause takes a new identity clause, and RESTART resets the generator in Oracle Database 18c and later.
ALTER TABLE invoices MODIFY (
invoice_id GENERATED ALWAYS AS IDENTITY (INCREMENT BY 5 CACHE 50)
);
ALTER TABLE invoices MODIFY (
invoice_id GENERATED ALWAYS AS IDENTITY (RESTART START WITH 1000)
);A change affects only values generated afterwards. Existing rows keep their ids. Restarting at a value that is already in the table leads to ORA-00001 as soon as the generator reaches an existing key.
Verifying the settings
Join the identity view to the sequence view to see the real values Oracle is using.
SELECT i.table_name,
i.column_name,
s.sequence_name,
s.increment_by,
s.cache_size,
s.last_number
FROM user_tab_identity_cols i
JOIN user_sequences s ON s.sequence_name = i.sequence_name
WHERE i.table_name = 'INVOICES';For a cached sequence, last_number is the next value that would be written to the dictionary after the current block, not the next id you will get. It is ahead of the last id by up to the cache size.
Common mistakes
- Expecting consecutive ids after rollbacks, errors or restarts.
- Using
START WITHto "skip" manually inserted ids, which the generator does not track. - Setting a huge
CACHEon a rarely used table. After each restart you lose most of a block for little gain. - Setting
NOCACHEon a hot insert table. Concurrent sessions then queue on the dictionary update. - Restarting a generator without checking the current maximum key.
Exercise
A table has id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY (START WITH 1 CACHE 20). Someone inserts rows with explicit ids 1 through 50 using a data load. Later, application code inserts with id NULL and starts getting ORA-00001 on the primary key. Why does this happen, and how would you fix it?
Show answer
The generator is independent of the table data and still starts at 1, so it produces ids that the load already used. Fix it by restarting the generator above the current maximum, for example ALTER TABLE t MODIFY (id GENERATED BY DEFAULT ON NULL AS IDENTITY (RESTART START WITH 51)) on 18c or later, using a value higher than SELECT MAX(id). To prevent a repeat, make loads omit the id, or use GENERATED ALWAYS.
Exercise
You insert a row into a table with an identity column and then roll back. The next committed insert gets an id two higher than the previous committed row. Is this a bug, and does NOCACHE prevent it?
Show answer
It is not a bug. Identity values come from a sequence, and sequence values are not returned on rollback. NOCACHE does not prevent this, because the value was consumed when the insert took it. NOCACHE only reduces the values lost when cached blocks are discarded, for example at an instance restart.