Problem
When using Drizzle ORM with Neon serverless PostgreSQL, passing an empty array or undefined to inArray() throws a database error:
Error [NeonDbError]: op ANY/ALL (array) requires array on right side
code: '42809'
severity: 'ERROR'
at execute (node_modules/@neondatabase/serverless/index.js:1:12345)
The query that triggers the error:
const filterByTags = async (tagIds: string[] | undefined) => {
const results = await db
.select()
.from(shares)
.where(inArray(shares.tagId, tagIds ?? []))
// ^^^^^^^^^^^ empty array causes the error
.execute();
return results;
};
Drizzle translates inArray(column, values) into column = ANY($1) in the generated SQL. When the values array is empty, PostgreSQL receives ANY('{}') or a null parameter, which violates the ANY/ALL operator requirement for a non-empty array argument.
Solution
Guard against empty or undefined arrays before passing them to inArray():
import { inArray, sql } from "drizzle-orm";
const filterByTags = async (tagIds: string[] | undefined) => {
const results = await db
.select()
.from(shares)
.where(
tagIds && tagIds.length > 0
? inArray(shares.tagId, tagIds)
: sql`false`
)
.execute();
return results;
};
For optional filters where an empty array should return all rows instead of none:
const filterByTags = async (tagIds: string[] | undefined) => {
const conditions = [];
if (tagIds && tagIds.length > 0) {
conditions.push(inArray(shares.tagId, tagIds));
}
const results = await db
.select()
.from(shares)
.where(conditions.length > 0 ? and(...conditions) : undefined)
.execute();
return results;
};
Why It Works
PostgreSQL's ANY() operator requires a non-empty array as its right-hand operand. Drizzle's inArray() generates column = ANY($1) without validating the array length, so an empty array produces an invalid SQL expression at the database level. By checking tagIds.length > 0 before calling inArray(), you prevent the invalid query from ever reaching PostgreSQL. Using sql\false`` as a fallback returns zero rows, which is the correct semantic for "match any of these zero values."
Context
- Neon serverless PostgreSQL with
@neondatabase/serverlessdriver - Drizzle ORM (
drizzle-ormanddrizzle-orm/neon-serverless) - The same error occurs with
notInArray()-- apply the same guard pattern - Standard
node-postgres(pg) may surface the same error with slightly different error formatting - This is a common pattern in search/filter endpoints where filter parameters are optional
- Drizzle does not plan to add automatic empty-array handling, treating it as application-level validation