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: a system versioned MariaDB table remembers every earlier row

Mariadb
~/tips/tip-mariadb-system-versioned-table

CREATE TABLE prices (

Lets you query what the data looked like at an earlier moment.

Who changed that price, and what was it before? MariaDB can keep the old versions of rows by itself, no triggers or audit table needed.

Add the clause when creating a table:

CREATE TABLE prices (
  item VARCHAR(20) PRIMARY KEY,
  price INT
) WITH SYSTEM VERSIONING;

For an existing table it’s ALTER TABLE prices ADD SYSTEM VERSIONING;. Updates and deletes now keep the previous row. A normal SELECT shows only current data, and you ask for history explicitly:

SELECT *, ROW_START, ROW_END FROM prices FOR SYSTEM_TIME ALL;
SELECT * FROM prices FOR SYSTEM_TIME AS OF TIMESTAMP '2026-01-15 12:00:00';

I find this lovely for small lookup tables that people edit by hand: prices, settings, permissions. It is the undo you wish you had.

History grows forever unless you trim it. DELETE HISTORY FROM prices BEFORE SYSTEM_TIME '2025-01-01'; removes old versions for good, so think before running it.

Two surprises to plan for. Changing the table structure later is refused by default, and you have to change system_versioning_alter_history to get past it. And a plain mariadb-dump saves only the current rows, so restoring from it loses the history; check the dump options of your version if the old rows matter.

It records what changed and when, but not who. For that, add a column your application fills in.

Further reading: System versioned tables

More Mariadb tips ALTER TABLE t ADD COLUMN z INT INVISIBLE; CREATE SEQUENCE s START WITH 100 INCREMENT BY 10; 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 \ All Mariadb tips (15) All topics

Link