opyeb sqllint

sqllint · Safety

Dangerous writes, NOT IN and N+1 queries

UPDATE and DELETE without WHERE, NOT IN and NULL, ORDER BY RAND, N+1

A read query that is slow is still reversible. A write query that goes wrong is often not. The statements below are perfectly valid SQL, and one missing condition turns each of them into something that touches every row.

UPDATE and DELETE without WHERE

UPDATE accounts SET plan = 'pro'; changes the plan of every account. DELETE FROM sessions; removes every session. When that is intended, TRUNCATE is faster; when it is not, there is rarely a way back. This tool marks an UPDATE or DELETE without WHERE as an error.

NOT IN and NULL

WHERE id NOT IN (1, 2, 3) behaves as expected while the list has no NULL. If the column itself can be NULL, the comparison becomes UNKNOWN and no row matches. When a subquery can produce NULL, NOT EXISTS is the safe form.

-- can return nothing when NULL is involved
WHERE id NOT IN (SELECT user_id FROM bans)

-- unaffected by NULL
WHERE NOT EXISTS (SELECT 1 FROM bans b WHERE b.user_id = users.id)

ORDER BY RAND()

Picking one row at random with ORDER BY RAND() sorts the whole table and takes the first. The cost grows quickly with row count. Narrow the key range first, or draw a random key and read the first row above it. PostgreSQL's TABLESAMPLE is another option.

N+1 queries

Reading a list and then looking up each item once is the N+1 pattern: a hundred rows become a hundred and one queries. A script that repeats the same single-row lookup three times or more is likely running inside a loop. Reading it in one IN list or joining it away removes the round trips.

PatternCostAlternative
100 single-row lookups100 round trips, connection heldone IN list or a JOIN
ORDER BY RAND() LIMIT 5sorts everythingsample a key range
NOT IN (subquery)empty result on NULLNOT EXISTS

The most effective habit is counting the affected rows with a SELECT using the same condition before any write. The diagnostics exist to keep that step from being skipped.

Questions

Will leaving out WHERE really change everything?

With no condition every row is a target. Some engines offer a safe-update mode that refuses it, but it is not the default.

Can N+1 be seen from SQL alone?

Not completely. A script that repeats the same single-row lookup is a strong signal; confirm it against the loop in the application code.

How is TRUNCATE different from DELETE?

TRUNCATE empties the table, usually cannot be rolled back and does not fire triggers. DELETE takes a condition and does fire triggers.

Paste a write statement and missing WHERE clauses and repeated lookups are reported first.

Open the tool

This article follows the published documentation of PostgreSQL 17, MySQL 8.4 and SQLite 3.46. Every table, column and value shown is synthetic.