Arrays
- Version
- 19
- Review
- Draft
Summary#
An array column holds an ordered list of values of one type. unnest turns elements into rows and array_agg collects rows into an array.
Syntax#
ARRAY['a', 'b']
column_name[1]
value = ANY (column_name)
column_name @> ARRAY[value]
unnest(column_name) WITH ORDINALITY
array_agg(column_name ORDER BY sort_column)
Example#
The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.
BEGIN;
CREATE TEMPORARY TABLE recipes (
recipe_id integer PRIMARY KEY,
name text NOT NULL,
labels text[] NOT NULL DEFAULT '{}'
);
INSERT INTO recipes VALUES
(1, 'soup', ARRAY['hot', 'vegan']),
(2, 'salad', '{cold,vegan,quick}'),
(3, 'toast', DEFAULT);
-- These arrays start at 1. A missing element is NULL.
SELECT name,
labels[1] AS first_label,
labels[2:3] AS slice,
cardinality(labels) AS size,
array_length(labels, 1) AS length_1
FROM recipes
ORDER BY recipe_id;
SELECT name
FROM recipes
WHERE 'vegan' = ANY (labels)
AND labels @> ARRAY['quick']
ORDER BY recipe_id;
SELECT r.name, u.position, u.label
FROM recipes AS r
CROSS JOIN LATERAL unnest(r.labels) WITH ORDINALITY AS u(label, position)
WHERE r.recipe_id = 2
ORDER BY u.position;
UPDATE recipes
SET labels = array_append(labels, 'new')
WHERE recipe_id = 3
RETURNING name, labels;
-- Collapse rows back into one ordered array.
SELECT array_agg(name ORDER BY name) AS names FROM recipes;
ROLLBACK;
Expected output#
name|first_label|slice|size|length_1
soup|hot|{vegan}|2|2
salad|cold|{vegan,quick}|3|3
toast|NULL|{}|0|NULL
(3 rows)
name
salad
(1 row)
name|position|label
salad|1|cold
salad|2|vegan
salad|3|quick
(3 rows)
name|labels
toast|{new}
(1 row)
names
{salad,soup,toast}
(1 row)
Common mistakes#
array_length(labels, 1) returns null for an empty array. Use cardinality(labels) when you need zero, and array_lower(labels, 1) if the array might start at a subscript other than 1. A default GIN index on an array supports @> and &&, but not the value = ANY (labels) form.
Version applicability#
unnest and array_agg were added in PostgreSQL 8.4. cardinality and WITH ORDINALITY require 9.4.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0