Memra

Postgres columns can hold lists — query them directly.

A column that holds a list

Postgres columns can be arrays. Each book carries a tags text[]. Work with them:

  • 'x' = ANY(tags) — does the array contain x?
  • tags @> ARRAY['a','b'] — does it contain all of these?
  • array_length(tags, 1) — how many elements (1 = first dimension)
  • unnest(tags) — expand the array into one row per element
SELECT title FROM books WHERE tags @> ARRAY['science'];

(Note: array_length of an empty array {} is NULL, not 0 — a classic gotcha.)

titletagsarray_lengthThe Glass Forest{bestseller,signed}2Quantum Mornings{science,new}2Rivers of Salt{}NULLSaltwater HymnsNULLNULLAn empty array has length NULL, not 0.
Two different absences sit in this column: Rivers of Salt has an array with nothing in it, Saltwater Hymns has no array at all. array_length returns NULL for both — so COALESCE(array_length(tags, 1), 0) is what you actually want when counting.
NORMAL ~/memra/learn/postgresql/arrays utf-8 LF