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 OR REPLACE TABLE rebuilds a table in one statement

Mariadb
~/tips/tip-mariadb-create-or-replace-table

CREATE OR REPLACE TABLE scratch (

Creates a table, replacing it if it already exists, so reruns of a script do not fail.

Setup scripts that I want to run twice usually start with DROP TABLE IF EXISTS and then CREATE TABLE. MariaDB lets you fold those two lines into one.

CREATE OR REPLACE TABLE scratch (
  id INT PRIMARY KEY,
  note VARCHAR(100)
);

If scratch does not exist, it is created. If it does, it is replaced by the new definition. The same OR REPLACE works for views and sequences, which makes it handy for scripts you rerun while you are still working things out. It also works with CREATE TABLE ... SELECT, so you can rebuild a summary table from a query on every run.

The caveat is the old data. Replacing means the old table is gone, rows included. Before MariaDB 13.2 the server behaves like DROP TABLE IF EXISTS followed by CREATE TABLE, so if the new statement fails, you end up with no table at all. From 13.2 the replace is atomic by default: the old table is kept under a backup name until the new one exists. Even then, the server still drops first in some cases, such as temporary tables or when the existing object is a view.

You cannot combine OR REPLACE with IF EXISTS. And a table you locked with LOCK TABLES stays locked after the statement. I would use it for scratch and derived tables, and keep real data out of reach of that keyword.

Further reading: MariaDB CREATE TABLE: OR REPLACE

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