Recently, I needed to query column of Array type at work, so I noted the common use cases of querying array in PostgreSQL.
-
Query if any element in the array meets the condition.
SELECT * FROM table_name WHERE 'match_value' = ANY(column_name);
-
Query if all elements in the array meet the condition.
SELECT * FROM table_name WHERE ARRAY['match_value1', 'match_value2'] <@ column_name; SELECT * FROM products WHERE 10 < ALL (values);
-
Check the length of an array.
SELECT * FROM table_name WHERE array_length(column_name, 1) = 2;
-
Query if an element at specific index meets the condition.
SELECT * FROM table_name WHERE column_name[1] = 'match_value';