brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: MariaDB CREATE SEQUENCE gives you numbers without AUTO_INCREMENT

Mariadb
~/tips/tip-mariadb-create-sequence

CREATE SEQUENCE s START WITH 100 INCREMENT BY 10;

Creates a sequence object that hands out numbers, usable as a column default.

AUTO_INCREMENT belongs to one table. Sometimes you want a counter that is not tied to a table, or one that several tables share. MariaDB has real sequences for that.

CREATE SEQUENCE s START WITH 100 INCREMENT BY 10;
SELECT NEXT VALUE FOR s;
SELECT NEXTVAL(s);

Each call returns the next number: 100, then 110, and so on. START WITH sets the first value and INCREMENT BY the step, which can be negative. The two forms NEXT VALUE FOR s and NEXTVAL(s) do the same thing.

A sequence works nicely as a column default:

CREATE SEQUENCE s1;
CREATE TABLE t1 (a INT PRIMARY KEY DEFAULT nextval(s1), b INT);
INSERT INTO t1 (b) VALUES (1);

Caveats from the docs. Values are cached, with a default CACHE of 1000, so after FLUSH TABLES or a server restart you can see gaps. Setting CACHE 1 removes most gaps, but the docs say inserts can become up to twice as slow and the binary log much bigger. A sequence with NOCYCLE (the default) returns an error once it runs out. And the min and max values cap what it can generate, so the very largest 64-bit numbers are out of reach.

If you only need ids for one table, plain AUTO_INCREMENT is still simpler.

Further reading: MariaDB CREATE SEQUENCE

More Mariadb tips ALTER TABLE t ADD COLUMN z INT INVISIBLE; CREATE OR REPLACE TABLE scratch ( mariadb --init-command="SET SESSION sql_mode='STRICT_ALL_TABLES'" mydb mariadb-admin -u root -p extended-status --relative --sleep=10 \ ALTER USER 'app'@'localhost' ACCOUNT LOCK; All Mariadb tips (15) All topics

Link