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: COLLATE NOCASE on a SQLite column makes email lookups ignore case

Sqlite
~/tips/tip-sqlite-collate-nocase

email TEXT COLLATE NOCASE UNIQUE

Declares a column case-insensitive so comparisons, uniqueness and its index ignore case.

People type [email protected] once and [email protected] the next time. With a plain text column those are two different values, and lower() in every query means the index on that column goes unused.

CREATE TABLE users (
  id INTEGER PRIMARY KEY,
  email TEXT COLLATE NOCASE UNIQUE
);
INSERT INTO users(email) VALUES ('[email protected]');
SELECT id FROM users WHERE email = '[email protected]';
1

The collation sits on the column, so every comparison with = ignores case, and so do ORDER BY and the unique constraint. A second insert of [email protected] now fails as a duplicate, which is what I want for logins. The index behind UNIQUE uses the same collation, so the lookup stays fast. The stored value keeps its original spelling.

You can also add it to one query, as in WHERE email = ? COLLATE NOCASE, but then the column index is not used for that comparison.

The big limit: NOCASE only knows the 26 ASCII letters. 'Ä' = 'ä' COLLATE NOCASE is false, so names with accents do not match. For full Unicode case folding you need the ICU extension or to store a normalized copy. LIKE is case-insensitive for ASCII by default anyway, with the same limit.

Further reading: SQLite datatypes and collating sequences

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