SQL array membership tests
WHERE 'sql' = ANY(tags) tests whether a PostgreSQL array contains a value without unnesting it. Its negation is not != ANY, which is the usual mistake.
- Returns
boolean- In this category
- 28 of 39
語法
value = ANY(array)
array @> array -- PostgreSQL
value MEMBER OF (collection) -- Oracle
Each block is a separate form. The support table and the examples show which engine takes which.
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | Not built in | no array type; EXISTS over OPENJSON |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | Not built in | no array type; JSON_CONTAINS for JSON |
| SQLite | Different name or syntax | EXISTS over json_each |
| Oracle | Different name or syntax | MEMBER OF condition over nested tables |
範例
PostgreSQL
SELECT * FROM articles WHERE 'sql' = ANY(tags);
PostgreSQL
SELECT * FROM articles WHERE tags @> ARRAY['sql', 'db'];
Oracle
SELECT * FROM articles WHERE 'sql' MEMBER OF (tags);
小知識
- x != ANY(arr) means 'not equal to at least one element' and is true for most arrays. The correct no-match test is NOT (x = ANY(arr)) or x != ALL(arr).
- tags @> ARRAY['sql', 'db'] requires every listed element; tags && ARRAY['sql', 'db'] requires at least one. A GIN index on the array column serves @>, <@ and &&.
- SQLite and MySQL hold lists in JSON or delimited text: EXISTS (SELECT 1 FROM json_each(tags) WHERE value = 'sql') is the portable shape there.
Questions about Array contains
Why does != ANY return true?
It is read as 'some element differs', which is almost always true. Negate the positive test, NOT ('sql' = ANY(tags)), or use != ALL for 'differs from every element'.
How do I index array membership?
Create a GIN index on the array column and write the test as tags @> ARRAY['sql']. The planner does not use a GIN index for 'sql' = ANY(tags), so the two spellings can have very different plans.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: PostgreSQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.