PostgreSQL’s IN and ANY operators: Which one to choose?
PostgreSQL provides two structures, IN and ANY, which are commonly used to compare values with sets. While the logical functionality of the two structures is essentially the same (both test set membership), they have subtle differences in syntax and performance.
Grammar Variations
IN has two syntax variants:
ANY also has two grammatical variants:
Use Cases
Performance Notes
In general, IN (collection) and ANY (collection) perform similarly, using an index scan if available. However, ANY (array) uses a sequential scan of the array, which may be less efficient for large arrays.
Comparison with = ANY (set)
Although IN (set) and = ANY (set) are logically equivalent, in some cases they may result in different query plans. Using IN forces PostgreSQL to create a temporary table for the collection, which may add overhead.
Versatility
ANY is more general than IN because it can be used with various operators (not just =). For example, you can use ANY with LIKE to check for pattern matching.
Exclude
To find rows that are not in a set, use NOT (column = ANY (set)). Alternatively, you can use ALL for this purpose.
NULL value
By default, rows with NULL values are not compared via IN or ANY. To include NULL values, you can use IS NOT TRUE with a comparison.
The above is the detailed content of IN vs. ANY in PostgreSQL: Which Operator Should You Choose?. For more information, please follow other related articles on the PHP Chinese website!