AI Hints
PostgreSQL · Lesson 38 of 120

Array Operators

Search inside lists.

⏱ 2 min read▶ Video at 33:10🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Which books are tagged twist? Which have both magic and dragons? Postgres has operators for asking questions about arrays.

  • Has twist?
  • Magic and dragons?
  • Operators

Searching tags

Equals any checks if a value is in the array. The contains operator, at sign greater than, checks for all the listed tags. Run it. Books with a twist, then books with both magic and dragons.

query.sqlsql
SELECT title, tags FROM books
WHERE 'twist' = ANY (tags);

SELECT title, tags FROM books
WHERE tags @> ARRAY['magic', 'dragons'];
Output
        title        |             tags
---------------------+------------------------------
 The Silent Orchard  | {series,twist}
 Code of the River   | {twist,fast-paced}
 Murder at Mill Lane | {twist,detective,bestseller}
 Deep Water          | {spy,twist}
 The Painted Door    | {series,twist}
(5 rows)

      title       |      tags
------------------+-----------------
 The Glass Forest | {dragons,magic}
(1 row)

Array operators

Equals any tests one value. Contains tests that every value is there. Contained by is the reverse. And overlap, double ampersand, tests for at least one shared value.

OperatorMeans
x = ANY(arr)x is in arr
arr @> otherhas all of other
arr <@ otherall in other
arr && othershare any

Summary

Any, contains and overlap search inside arrays, and a GIN index makes them fast. Next, turning arrays into rows and back.

Key takeaways
  • ANY
  • @>
  • &&
Next up: unnest and array_agg — rows and lists