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: RETURNING gives you the rows a SQLite INSERT, UPDATE or DELETE touched

Sqlite
~/tips/tip-sqlite-returning-clause

DELETE FROM users WHERE active = 0 RETURNING id, email;

Gets back ids and values of changed rows from the same statement that changed them.

After an insert you often need the new id, and after a cleanup you want to know which rows went. Since 3.35, SQLite can hand those rows back in the same statement.

DELETE FROM users WHERE active = 0 RETURNING id, email;
2|[email protected]

The rows come back as a normal result set, one per deleted row, with the columns you list. It works on INSERT and UPDATE too:

INSERT INTO counter VALUES ('home', 1)
  ON CONFLICT(name) DO UPDATE SET hits = hits + 1
  RETURNING hits;

That one statement bumps the counter and tells you the new value, with no second query and no race between the two.

For a delete in the shell, I like to run it with RETURNING first inside a transaction, read what it printed, and only then COMMIT or ROLLBACK. It is a cheap way to see what a cleanup will remove.

The docs list a few limits. The returned rows reflect the change made by the statement itself, but not changes made afterwards by triggers. RETURNING is not allowed in a statement inside a trigger. And the order of the returned rows is not defined, so add your own sort later if you need one. If your driver bundles a SQLite older than 3.35, you get a syntax error; check with SELECT sqlite_version();.

Further reading: SQLite RETURNING clause

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