DBAtlas · Database operations atlas

Create a sequence / auto-increment value

Oracle

-- Sequence
CREATE SEQUENCE customer_seq START WITH 1 INCREMENT BY 1 NOCACHE;
SELECT customer_seq.NEXTVAL FROM dual;

-- or an identity column (12c+)
CREATE TABLE customer (id NUMBER GENERATED ALWAYS AS IDENTITY, name VARCHAR2(100));

The classic method is CREATE SEQUENCE + NEXTVAL/CURRVAL. Since 12c, GENERATED AS IDENTITY columns are also supported. A CACHE value improves performance but gaps can occur.

PostgreSQL

-- Sequence
CREATE SEQUENCE customer_seq START 1 INCREMENT 1;
SELECT nextval('customer_seq');

-- Modern method: identity column
CREATE TABLE customer (id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text);
-- Classic: serial (creates a sequence behind the scenes)
CREATE TABLE logs (id serial PRIMARY KEY, message text);

GENERATED ... AS IDENTITY is SQL standard and recommended; serial is the legacy shorthand. Access manually with nextval/currval. The value can be reset with setval.

MySQL

-- AUTO_INCREMENT column
CREATE TABLE customer (id BIGINT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100));

-- Set the starting value
ALTER TABLE customer AUTO_INCREMENT = 1000;

-- Get the last inserted value
SELECT LAST_INSERT_ID();

MySQL has no standalone (standard) sequence object; an AUTO_INCREMENT column is used (one per table, must be indexed). MariaDB 10.3+ supports CREATE SEQUENCE.

SQL Server

-- IDENTITY column
CREATE TABLE customer (id INT IDENTITY(1,1) PRIMARY KEY, name NVARCHAR(100));

-- Standalone sequence object
CREATE SEQUENCE customer_seq AS INT START WITH 1 INCREMENT BY 1;
SELECT NEXT VALUE FOR customer_seq;

IDENTITY(seed,increment) is bound to a table column. CREATE SEQUENCE (2012+) provides a counter independent of tables that can be shared across tables; values are fetched with NEXT VALUE FOR.

MongoDB

// MongoDB has no auto counter; counter pattern with findOneAndUpdate
db.counters.findOneAndUpdate(
  { _id: "customer" },
  { $inc: { seq: 1 } },
  { upsert: true, returnDocument: "after" }
);

The default _id is an ObjectId (already unique and roughly increasing). If a sequential integer is needed, generate it atomically with $inc in a separate counters collection.

Redis

# Atomic counter
INCR customer:id
# or with a specific step
INCRBY customer:id 10

INCR/INCRBY are atomic and ideal for generating unique increasing IDs in distributed environments. If the key does not exist, it starts from 0.

Elasticsearch

# Not applicable: Elasticsearch does not offer a sequence object. Document IDs are assigned automatically;
# the internal _seq_no and _primary_term fields are used for concurrency control.
POST logs/_doc
{ "message": "sample" }

If you POST without an ID, ES assigns a random unique _id (not increasing). _seq_no is an internal sequence number that increases with each write, but it is for optimistic concurrency, not an application counter.

Open in DBAtlas →