RefLib

Reference library for AI

Back

postgresql_16:3.5.15.5 Searching in Arrays

PostgreSQL 16 > The SQL Language > Data Types > Arrays > Searching in Arrays

To search for a value in an array, each value must be checked. This can be done manually, if you know the size of the array. For example: SELECT * FROM sal_emp WHERE pay_by_quarter[1] = 10000 OR pay_by_quarter[2] = 10000 OR pay_by_quarter[3] = 10000 OR pay_by_quarter[4] = 10000; However, this quickly becomes tedious for large arrays, and is not helpful if the size of the array is unknown. An alternative method is described in (see postgresql_16:3.6.24). The above query could be replaced by: SELECT * FROM sal_emp WHERE 10000 = ANY (pay_by_quarter); In addition, you can find rows where the array has all values equal to 10000 with: SELECT * FROM sal_emp WHERE 10000 = ALL (pay_by_quarter);

Alternatively, the generate_subscripts function can be used. For example: SELECT * FROM (SELECT pay_by_quarter, generate_subscripts(pay_by_quarter, 1) AS s FROM sal_emp) AS foo WHERE pay_by_quarter[s] = 10000; This function is described in (see functions-srf-subscripts).

You can also search an array using the && operator, which checks whether the left operand overlaps with the right operand. For instance: SELECT * FROM sal_emp WHERE pay_by_quarter && ARRAY[10000]; This and other array operators are further described in (see postgresql_16:3.6.19). It can be accelerated by an appropriate index, as described in (see postgresql_16:3.8.2).

You can also search for specific values in an array using the array_position and array_positions functions. The former returns the subscript of the first occurrence of a value in an array; the latter returns an array with the subscripts of all occurrences of the value in the array. For example: SELECT array_position(ARRAY['sun','mon','tue','wed','thu','fri','sat'], 'mon'); array_position ---------------- 2 (1 row) SELECT array_positions(ARRAY[1, 4, 3, 1, 3, 4, 2, 1], 1); array_positions ----------------- {1,4,8} (1 row)

Tip

Arrays are not sets; searching for specific array elements can be a sign of database misdesign. Consider using a separate table with a row for each item that would be an array element. This will be easier to search, and is likely to scale better for a large number of elements.

Back