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: SQLite iif() is a short CASE expression with several branches

Sqlite
~/tips/tip-sqlite-iif-function

SELECT name, iif(qty > 0, 'in stock', 'sold out') AS state

Picks a value based on conditions, without writing a full CASE expression.

CASE WHEN … THEN … ELSE … END is correct, but it is a lot of typing for a simple choice. SQLite has a shorter way, borrowed from other databases.

SELECT name, iif(qty > 0, 'in stock', 'sold out') AS state
FROM products;

iif(X, Y, Z) returns Y when X is true and Z otherwise. SQLite documents it as shorthand for CASE WHEN X THEN Y ELSE Z END, with the same bytecode and short-circuit evaluation, so it costs nothing extra.

Newer versions go further. The arguments are taken in pairs of condition and value, and an odd last argument is the default:

SELECT iif(score >= 90, 'A', score >= 80, 'B', 'C') FROM grades;

With an even number of arguments and no true condition, you get NULL. if() works as an alternative spelling.

The caveat is the version. The three-argument form has been around since SQLite 3.32. The two-argument form and if() need 3.48.0, and more than three arguments need 3.49.0. If your sqlite3 comes from an old distribution, the long form gives you a syntax error or a wrong answer, so check SELECT sqlite_version(); first. For code that has to run on older libraries, plain CASE is still the safe choice.

Further reading: SQLite core functions: iif

More Sqlite tips SELECT unixepoch('2026-01-01 00:00:00'); 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; sqlite> .once users.csv All Sqlite tips (27) All topics

Link