← Back to SQL, page 23

sql-0441 · Medium mid

The application sends a query with 50,000 ids in an IN list. It is slow and sometimes fails. What would you do instead?

Very large IN lists bloat the SQL text, slow parsing and planning, and can hit parameter limits (SQLite allows 32,766 parameters by default in recent versions). Load the ids into a temporary table and join, pass them as one array parameter in PostgreSQL (= ANY($1)), or better, express the selection as a query so the ids never leave the database.

Full answer

Alternatives:

  • Temporary table: insert ids in batches into tmp_ids(id PRIMARY KEY), then SELECT ... FROM items JOIN tmp_ids USING (id). The planner sees a real table with statistics.
  • Array parameter (PostgreSQL): WHERE id = ANY($1::bigint[]) sends one parameter regardless of length and keeps one cached plan.
  • JSON parameter: json_each(?) in SQLite or jsonb_array_elements in PostgreSQL turns a JSON array into rows.
  • Push the logic down: if the ids came from another query, use that query as a subquery or join instead of round-tripping ids through the application.
  • Batching: split into chunks of a few hundred when nothing else is possible.

The parameter limit for SQLite is SQLITE_MAX_VARIABLE_NUMBER, 32,766 by default since 3.32; older builds used 999. These limits are stated from documentation and were not run here.

Key points

  • Huge IN lists slow parsing and hit limits
  • Temp tables give real joins
  • Array parameters keep one plan
  • JSON arrays can become rows
  • Avoid round-tripping ids

Common mistakes

  • Concatenating ids into SQL text
  • Assuming no parameter limit exists

Follow-ups

  • How does json_each work in SQLite?
  • When is batching acceptable?

Tips

  • Prefer moving the logic into SQL