Sub topic 1
Declaring array columns
PostgreSQL lets any column hold an array of values instead of a single value. This chapter covers how to declare such a column, what the declaration does and does not enforce, and how to add constraints so the data stays clean. Later chapters cover writing values, reading elements, and searching.
Prerequisites
This chapter assumes you can do the following:
- Write basic SQL:
SELECT,INSERT,UPDATE, andWHERE. - Create tables and choose column data types.
- Reason about
NULLand three-valued logic, where a comparison can be true, false, or unknown. - Run statements in
psqlor another PostgreSQL client.
Examples were written for a current PostgreSQL release (13 or later). Where a feature depends on the version, the text says so.
What an array column is
An array column stores an ordered list of values of one element type. Every element has the same type, and one row can hold any number of elements. You use this when a value is a small list that belongs to one row, such as the tags on a blog post.
PostgreSQL creates an array type automatically for almost every type you define or use. Each base type has a matching array type, and you name it by adding [] to the element type. For example, text[] is an array of text, and integer[] is an array of integer.
The declaration syntax
The standard form appends square brackets to the element type:
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);This table is used throughout the tutorial. The tags column is a text[]. It cannot be NULL, and a row inserted without tags gets an empty array.
PostgreSQL accepts three equivalent spellings of the same column type:
CREATE TABLE spelling_demo (
a text[],
b text ARRAY,
c text ARRAY[4]
);All three columns have the type text[]. The ARRAY keyword form comes from the SQL standard. The bracket form is more common in PostgreSQL code, and most teams pick one and stay with it.
You can declare arrays of nearly any type. These all work:
- Built-in types such as
integer[],bigint[],uuid[],boolean[],date[], andtimestamptz[]. - Types with modifiers such as
varchar(20)[]andnumeric(8,2)[]. - Enum types, for example
mood[]afterCREATE TYPE mood AS ENUM (...). - Composite types, which are row-like types you create with
CREATE TYPE. - Domains, which are types with attached constraints. A domain can also be defined over an array, as shown later.
Sizes and dimensions are not enforced
This is the most common surprise for newcomers. You may write a size or extra bracket pairs in a declaration, but PostgreSQL ignores them. The documentation states that the current implementation ignores any supplied array size limits, and it also does not enforce the number of dimensions.
CREATE TABLE shape_demo (
a integer[3],
b integer[][]
);
INSERT INTO shape_demo (a, b)
VALUES ('{1,2,3,4,5}', '{{1,2},{3,4}}');
SELECT cardinality(a) AS a_elements,
cardinality(b) AS b_elements,
array_ndims(b) AS b_dims
FROM shape_demo;The insert succeeds even though a was declared as integer[3] and holds five elements. The query returns 5, 4, and 2. Column b was declared with two pairs of brackets, but it would accept a one-dimensional array as well.
In practice this means:
integer[],integer[3], andinteger[][]are the same type as far as PostgreSQL is concerned.- The brackets document your intent, but they do not protect it.
- If you need a maximum length or a fixed number of dimensions, you must write a
CHECKconstraint.
The hard limits that do exist are these. An array can have at most 6 dimensions, and like any field value it cannot exceed 1 GB in size. You are very unlikely to reach either, and you would have a design problem long before you did.
Inspecting the type of a column
Behind the scenes, PostgreSQL names each array type with a leading underscore. The array type for text is _text, and the one for integer is _int4. You rarely type these names, but you see them in catalogs and some tool output.
Three ways to check what a column is:
SELECT pg_typeof(tags) AS column_type,
pg_typeof(tags[1]) AS element_type
FROM posts
LIMIT 1;
SELECT column_name, data_type, udt_name
FROM information_schema.columns
WHERE table_name = 'posts'
AND column_name = 'tags';The first query needs at least one row in posts. It returns text[] and text. The second query returns ARRAY as the data_type and _text as the udt_name. In psql, the command \d posts shows the column as text[].
Keep the second result in mind when you write code that reads the catalog. information_schema reports the generic word ARRAY and puts the element information in udt_name. The pg_attribute catalog combined with format_type gives the friendlier text[] form.
Defaults, NOT NULL, and the empty array
An array column can be NULL, or it can hold an empty array. These are different values. A NULL array means "unknown or not set". An empty array {} means "a list with zero elements". Mixing them in one column makes every query harder, because you have to handle both.
The usual choice for list-like data is to forbid NULL and default to an empty array:
ALTER TABLE posts
ADD COLUMN reviewers text[] NOT NULL DEFAULT '{}';You can write the default in either of two ways:
-- String literal form, coerced to the column's type
DEFAULT '{}'
-- Constructor form, which needs an explicit cast
DEFAULT ARRAY[]::text[]The constructor needs the cast because ARRAY[] alone has no element to infer a type from. PostgreSQL reports an error such as "cannot determine type of empty array". The quoted literal form does not have this problem, because the column's type tells PostgreSQL how to read it.
In PostgreSQL 11 and later, adding a column with a constant default like this does not rewrite the table, so it is fast even on large tables.
Constraining array columns
Because the declaration does not limit length or contents, use CHECK constraints for rules you care about. A CHECK constraint runs on every insert and update and rejects the row if the expression is false.
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
sizes varchar(3)[] NOT NULL DEFAULT '{}',
prices numeric(8,2)[] NOT NULL DEFAULT '{}',
CONSTRAINT sizes_max_five
CHECK (cardinality(sizes) <= 5),
CONSTRAINT sizes_no_null_elements
CHECK (array_position(sizes, NULL) IS NULL)
);
INSERT INTO products (name, sizes, prices)
VALUES ('Tee', '{S,M,L}', '{9.5,12}');Several things happen in this example:
- The element modifiers apply to each element. The prices are stored as
9.50and12.00, becausenumeric(8,2)rounds each element to two decimals. A size such asXXXLis rejected because it is longer than 3 characters. cardinality(sizes) <= 5limits the number of elements.cardinalitycounts all elements in all dimensions and returns0for an empty array.array_position(sizes, NULL) IS NULLrejects arrays that contain aNULLelement. The function findsNULLelements, and it returnsNULLwhen nothing matches, including for an empty array.
These inserts fail:
-- Six elements: violates sizes_max_five
INSERT INTO products (name, sizes)
VALUES ('Hoodie', '{XS,S,M,L,XL,XXL}');
-- Contains a NULL element: violates sizes_no_null_elements
INSERT INTO products (name, sizes)
VALUES ('Cap', '{S,NULL}');A CHECK constraint passes when its expression is NULL, not only when it is true. If the column allowed NULL, then cardinality(sizes) <= 5 would evaluate to NULL for a NULL array and the row would be accepted. Pairing CHECK with NOT NULL closes that gap.
Reusable rules with domains
If several tables need the same array rule, define a domain over the array type and use the domain as the column type:
CREATE DOMAIN tag_list AS text[]
NOT NULL
DEFAULT '{}'
CHECK (cardinality(VALUE) <= 10);
CREATE TABLE articles (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tags tag_list
);Inside the domain's CHECK, the word VALUE stands for the value being tested. Every column that uses tag_list gets the same default and the same limit, and you change the rule in one place with ALTER DOMAIN.
The trade-off is that a domain hides the type from casual reading. A column shown as tag_list does not tell the reader it is an array until they look up the domain. Operators and functions still work on it, because PostgreSQL treats a domain over an array as that array type when it resolves them.
Changing an existing column to an array
A common migration turns a single-value column into a list. Use ALTER COLUMN ... TYPE with a USING clause that tells PostgreSQL how to convert existing values:
CREATE TABLE tickets (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
category text,
labels text
);
INSERT INTO tickets (category, labels)
VALUES ('billing', 'urgent,vip'), (NULL, NULL);
-- One value becomes a one-element array; NULL stays NULL
ALTER TABLE tickets
ALTER COLUMN category TYPE text[]
USING CASE WHEN category IS NULL THEN '{}' ELSE ARRAY[category] END;
-- A comma-separated string becomes a multi-element array
ALTER TABLE tickets
ALTER COLUMN labels TYPE text[]
USING string_to_array(labels, ',');Both statements rewrite the table, so they take a lock and take time on large tables. Plan them for a quiet period. After the second statement, NULL in labels stays NULL, because string_to_array returns NULL for a NULL input. Add COALESCE(string_to_array(labels, ','), '{}') to the USING expression if you want empty arrays instead. Any default on the old column must be dropped before the type change and set again afterward, because the old default cannot be converted automatically.
Storage and update behavior
An array is stored as one value inside the row. PostgreSQL keeps a small header with the element type and dimensions, followed by the elements. When the row grows large (roughly 2 kB), PostgreSQL compresses it or moves it to a side table through its TOAST mechanism, like any large value.
Two consequences matter when you design a column:
- An update that changes one element writes a new copy of the entire array, and therefore of the row version. Appending a tag to a short list is cheap. Updating one element in an array of thousands is not.
- The element values are not individually visible to the database's storage layer. There are no per-element statistics or foreign keys. This is why a later chapter compares arrays with related tables.
Quick reference
| Goal | Declaration or constraint |
|---|---|
| Array of text | `tags text[]` |
| Same, standard syntax | `tags text ARRAY` |
| Never `NULL`, empty by default | `tags text[] NOT NULL DEFAULT '{}'` |
| Limit the number of elements | `CHECK (cardinality(tags) <= 10)` |
| Forbid `NULL` elements | `CHECK (array_position(tags, NULL) IS NULL)` |
| Element length limit | `varchar(20)[]` |
| Reuse a rule across tables | `CREATE DOMAIN ... AS text[] CHECK (...)` |
Common mistakes
- Trusting
integer[3]to limit the length. It does not. Add aCHECKconstraint. - Writing
DEFAULT ARRAY[]without a cast. Use'{}'orARRAY[]::text[]. - Allowing both
NULLand{}in one column when you only mean "no items". UseNOT NULL. - Declaring
text[][]to mean "an array of arrays of strings" and expecting nested lists of different lengths. Multidimensional arrays must be rectangular, and a later chapter covers them. - Forgetting that
CHECK (cardinality(col) <= 5)accepts aNULLarray.
Exercise
You declare scores integer[2] NOT NULL DEFAULT '{}' and then run INSERT INTO t (scores) VALUES ('{10,20,30,40}'). Does the insert succeed? What single constraint would you add so that the column accepts at most two elements, and does that constraint allow the default value?
Show answer
The insert succeeds, because PostgreSQL ignores the [2] size in the declaration. To enforce the limit, add CHECK (cardinality(scores) <= 2). The default '{}' has cardinality 0, so it passes the constraint. Because the column is NOT NULL, the check cannot be bypassed with a NULL array.
Exercise
A column is declared labels text[] with no NOT NULL and no default. A row has labels = NULL. Another row has labels = '{}'. Both rows satisfy CHECK (cardinality(labels) <= 5). Why does the NULL row pass, and how would you change the declaration so only the empty-array form can represent "no labels"?
Show answer
A CHECK constraint rejects a row only when the expression is false. For a NULL array, cardinality returns NULL, so NULL <= 5 is NULL and the row is accepted. To allow only the empty array for "no labels", declare labels text[] NOT NULL DEFAULT '{}', which prevents NULL from being stored at all.
Exercise
Write a declaration for a reminders column that holds timestamptz values, is never NULL, defaults to an empty array, and allows no more than 3 reminders per row.
Show answer
reminders timestamptz[] NOT NULL DEFAULT '{}' CHECK (cardinality(reminders) <= 3). The column constraint form works because the CHECK refers only to this column. You can also name it with CONSTRAINT reminders_max_three CHECK (...).