Sub topic 11
Arrays
This chapter assumes you can write CREATE TABLE, INSERT and SELECT, and that you know what a column type and a constraint are. It also assumes you can run queries in psql or another client. You should have read the earlier chapters on text and casting.
What an array column is
Every PostgreSQL type has a matching array type. You get it by adding [] to the type name: integer[], text[], timestamptz[]. An array is an ordered list of values that all have the same element type, stored inside a single column of a single row.
That makes arrays a modeling choice. The other option is a child table with one row per value. Arrays suit small, ordered or unordered lists that belong to one row and are read or written as a unit. Tags on a post, a few phone numbers and a list of scores are typical.
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);
INSERT INTO posts (title, tags) VALUES
('Intro to types', ARRAY['sql', 'postgres']),
('Arrays in depth', '{"sql","arrays","postgres"}'),
('Untagged', '{}');The example shows two ways to write an array value:
- Constructor syntax:
ARRAY['sql', 'postgres']. Each element is an ordinary expression, so you can use column references and function calls inside it. - Literal syntax:
'{"sql","arrays","postgres"}'. This is a quoted string in braces. PostgreSQL parses it as the column's array type. Elements that contain spaces, commas, braces or quotes must be double-quoted inside the braces.
An empty array is '{}' or ARRAY[]::text[]. The constructor needs the cast because an empty ARRAY[] gives PostgreSQL no element type to infer.
Subscripts, slices and lengths
Array subscripts start at 1, not 0. A slice uses [low:high] and includes both ends.
SELECT title,
tags[1] AS first_tag,
tags[2:3] AS middle_tags,
tags[10] AS out_of_range,
array_length(tags, 1) AS len_1,
cardinality(tags) AS len_2
FROM posts
ORDER BY id;Three behaviors catch people out:
- A subscript outside the array returns
NULL. It does not raise an error. A slice outside the array returns an empty array. array_length(tags, 1)returnsNULLfor an empty array, not 0. The second argument is the dimension.cardinality(tags)returns 0 for an empty array, so prefer it when you want a count.- Subscripts also work on the left side of an
UPDATE.SET tags[2] = 'db'replaces one element. If you assign past the end, PostgreSQL extends the array and fills any gap withNULL.
Searching arrays
Three operators cover most array filters. They compare whole arrays and work well with an index.
| Operator | Meaning | Example (true) |
|---|---|---|
| `@>` | left contains every element of right | `ARRAY[1,2,3] @> ARRAY[2]` |
| `<@` | left is contained by right | `ARRAY[2] <@ ARRAY[1,2,3]` |
| `&&` | the arrays share at least one element | `ARRAY[1,2] && ARRAY[2,9]` |
For a single value, use value = ANY(array):
SELECT title FROM posts WHERE tags @> ARRAY['sql', 'arrays']; -- has both tags
SELECT title FROM posts WHERE tags && ARRAY['arrays', 'json']; -- has either tag
SELECT title FROM posts WHERE 'postgres' = ANY (tags); -- has this tagContainment ignores order and duplicates. ARRAY[1,2,3] @> ARRAY[3,3,1] is true.
Indexing
A B-tree index on an array column only helps whole-array equality and ordering. For element searches, use a GIN index:
CREATE INDEX posts_tags_idx ON posts USING gin (tags);This index supports @>, <@, && and =. It does not support 'sql' = ANY (tags). If you filter on one tag often, write it as tags @> ARRAY['sql'] so the planner can use the index.
Changing arrays
An array column is replaced as a whole value, even when you change one element. The functions below return a new array, so you assign the result back:
UPDATE posts SET tags = array_append(tags, 'tutorial') WHERE id = 1;
UPDATE posts SET tags = array_remove(tags, 'sql') WHERE id = 1;
UPDATE posts SET tags = tags || ARRAY['a', 'b'] WHERE id = 2;array_append adds one element at the end. array_remove removes every element equal to the value. The || operator concatenates two arrays, or an array and an element. array_cat does the same as || for two arrays.
Large arrays are expensive to update. Each update writes a new copy of the row, and PostgreSQL stores a large array out of line in TOAST (its side storage for big values), so changing one element rewrites the whole array. If many sessions append to the same list concurrently, they also contend for the same row.
Moving between arrays and rows
unnest turns an array into a set of rows. array_agg does the reverse by collecting rows into an array.
SELECT p.id, t.tag
FROM posts AS p
CROSS JOIN LATERAL unnest(p.tags) AS t(tag)
ORDER BY p.id, t.tag;
SELECT array_agg(title ORDER BY title) AS all_titles
FROM posts;The unnest query returns no rows for posts with an empty array, because the lateral function yields nothing for them. Use LEFT JOIN LATERAL ... ON true if you need those posts to appear with a NULL tag.
Use unnest with GROUP BY to count tag usage. Collecting values with array_agg is also a quick way to build a list for display.
NULLs, dimensions and casts
An array can hold NULL elements: ARRAY[1, NULL, 3] is valid. Comparisons that involve those elements follow three-valued logic. For example, 2 = ANY (ARRAY[1, NULL]) returns NULL, not false, because the NULL element might have been 2. A WHERE clause treats that result as not matching, but NOT of it is also NULL, which can surprise you in negated filters.
Arrays can have more than one dimension, as in ARRAY[[1,2],[3,4]]. Every sub-array at the same level must have the same length, so PostgreSQL rejects ARRAY[[1,2],[3]]. Nested data that is uneven belongs in jsonb or a table.
Declared sizes are not enforced. A column declared integer[3] accepts arrays of any length and any number of dimensions. If you need a length limit, add a check constraint:
ALTER TABLE posts
ADD CONSTRAINT posts_tags_max CHECK (cardinality(tags) <= 10);Casting a string to an array type parses the literal syntax, and a malformed literal raises an error:
SELECT '{1,2,3}'::integer[] AS ok;
SELECT '{1,two,3}'::integer[]; -- ERROR: invalid input syntax for type integer: "two"
SELECT '1,2,3'::integer[]; -- ERROR: malformed array literal: "1,2,3"You can also cast between array types when the element types can be cast: ARRAY[1,2,3]::bigint[]. string_to_array('a,b,c', ',') and array_to_string(tags, ', ') convert between delimited text and text[] without writing braces by hand.
When not to use an array
Arrays work against you when you need any of the following:
- Foreign keys. An array element cannot reference another table. If each tag must exist in a
tagstable, use a junction table. - Per-value data. If each tag needs a creation date or an author, it is an entity and needs its own row.
- Frequent single-element updates on large lists, for the rewrite reasons above.
- Joins and aggregates on elements across many rows, where a normal table is simpler and has better statistics for the planner.
Exercise
Write a query that returns the titles of posts whose tags array contains both 'sql' and 'postgres', in a form that the GIN index posts_tags_idx can use. Then say why 'sql' = ANY (tags) would not use that index.
Show answer
SELECT title FROM posts WHERE tags @> ARRAY['sql', 'postgres']; The GIN operator class for arrays supports the operators @>, <@, && and =. The ANY form is a different expression that the index does not support, so use tags @> ARRAY['sql'] for a single-tag filter that should use the index.
Exercise
What do cardinality('{}'::text[]), array_length('{}'::text[], 1) and (ARRAY['a','b'])[3] each return?
Show answer
cardinality returns 0, array_length returns NULL (an empty array has no first dimension), and the out-of-range subscript returns NULL without raising an error.