Full answer
Alternatives:
- Temporary table: insert ids in batches into
tmp_ids(id PRIMARY KEY), thenSELECT ... 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 orjsonb_array_elementsin 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