Sequence / Auto-Increment-Wert anlegen
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));Die klassische Methode ist CREATE SEQUENCE + NEXTVAL/CURRVAL. Seit 12c werden auch GENERATED AS IDENTITY-Spalten unterstützt. Ein CACHE-Wert verbessert die Performance, es können aber Lücken entstehen.
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 ist SQL-Standard und empfohlen; serial ist die Legacy-Kurzform. Manueller Zugriff mit nextval/currval. Der Wert lässt sich mit setval zurücksetzen.
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 hat kein eigenständiges (standardkonformes) Sequence-Objekt; es wird eine AUTO_INCREMENT-Spalte verwendet (eine pro Tabelle, muss indiziert sein). MariaDB 10.3+ unterstützt 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) ist an eine Tabellenspalte gebunden. CREATE SEQUENCE (2012+) liefert einen tabellenunabhängigen Zähler, der von mehreren Tabellen genutzt werden kann; Werte werden mit NEXT VALUE FOR abgerufen.
MongoDB
// MongoDB has no auto counter; counter pattern with findOneAndUpdate
db.counters.findOneAndUpdate(
{ _id: "customer" },
{ $inc: { seq: 1 } },
{ upsert: true, returnDocument: "after" }
);Die Standard-_id ist eine ObjectId (bereits eindeutig und annähernd steigend). Wird ein fortlaufender Integer benötigt, diesen atomar mit $inc in einer separaten counters-Collection erzeugen.
Redis
# Atomic counter
INCR customer:id
# or with a specific step
INCRBY customer:id 10INCR/INCRBY sind atomar und ideal, um in verteilten Umgebungen eindeutige, steigende IDs zu erzeugen. Existiert der Key nicht, beginnt er bei 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" }Bei POST ohne ID vergibt ES eine zufällige eindeutige _id (nicht steigend). _seq_no ist eine interne Sequenznummer, die mit jedem Schreibvorgang steigt, dient aber der Optimistic Concurrency und nicht als Anwendungszähler.