Allocate IDs with a sequence

Create a sequence for an application-side ID allocator. Run all statements in one session so CURRVAL refers to the value obtained there. Sequence values are not a substitute for a unique constraint on the target table.

CREATE DATABASE cookbook_sequence;
USE cookbook_sequence;
CREATE SEQUENCE order_id INCREMENT 5 START WITH 10;
SELECT NEXTVAL('order_id') AS first_id;
SELECT NEXTVAL('order_id') AS second_id;
SELECT CURRVAL('order_id') AS current_id;
DROP SEQUENCE order_id;
DROP DATABASE cookbook_sequence;

The two NEXTVAL calls return 10 and 15; CURRVAL returns 15. An unused or rolled-back allocation can leave a gap, so do not use sequence values as a gap-free invoice counter. See the v4.2.4 source test.