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: STRICT tables make SQLite reject the wrong data type

Sqlite
~/tips/tip-database-sqlite-strict-tables

CREATE TABLE readings (

Makes a SQLite table refuse values that don't match the column's declared type.

SQLite is famously relaxed about types. Declare a column INTEGER, insert 'abc', and SQLite shrugs and stores the text. That flexibility is on purpose, but if you’re used to PostgreSQL it feels like the database is quietly lying to you. Since SQLite 3.37.0 you can switch it off per table with one keyword.

Add STRICT after the closing bracket of CREATE TABLE:

CREATE TABLE readings (
  id      INTEGER PRIMARY KEY,
  sensor  TEXT NOT NULL,
  value   REAL
) STRICT;

Now a bad insert fails instead of slipping through:

INSERT INTO readings (sensor, value) VALUES ('livingroom', 'warm');
-- fails: cannot store TEXT value in REAL column readings.value

SQLite still converts values when it can do that without losing anything, the way other databases do, so '21.5' becomes the number 21.5. Only values that can’t be converted are refused, with an SQLITE_CONSTRAINT_DATATYPE error. A strict table also requires a type on every column, and the type has to be one of INT, INTEGER, REAL, TEXT, BLOB or ANY. That last one is the escape hatch: an ANY column keeps accepting anything, without conversion.

I’d use it for every new table in a small project or a self-written tool where you control the schema. Mistakes show up at insert time, which is a lot nicer than finding text in a number column months later.

The caveats: you can’t turn an existing table into a strict one with ALTER TABLE; you’d create a new strict table and copy the data over. And types like VARCHAR(50), DATETIME or BOOLEAN are not allowed in a strict table, so schemas copied from MySQL need some editing (dates usually become TEXT or INTEGER). Finally, a database with a strict table can only be opened by SQLite 3.37.0 or newer, which matters if an older tool on another machine also reads the file.

Further reading: SQLite: STRICT Tables, SQLite: Datatypes In SQLite

More Sqlite tips SELECT unixepoch('2026-01-01 00:00:00'); SELECT name, iif(qty > 0, 'in stock', 'sold out') AS state sqlite3 -bail app.db < migrate.sql CREATE INDEX 'orders_user_id' ON 'orders'('user_id'); –> users(id) CREATE INDEX users_active_email ON users(email) WHERE active = 1; All Sqlite tips (27) All topics

Link