Sub topic 1
Declaring Array Columns
PostgreSQL arrays let one column hold multiple values of the same data type. An array column is useful when a row naturally owns a small, bounded list, such as labels, alternate phone numbers, or measurement readings.
Prerequisites
This chapter assumes that you can write basic CREATE TABLE, INSERT, and SELECT statements. You should also understand column data types, primary keys, NULL, and default values. The examples use PostgreSQL and can be run in psql or another PostgreSQL client.
Choosing an Array Type
An array type is written by adding [] to an element type:
text[]stores text values.integer[]stores integer values.date[]stores dates.uuid[]stores UUID values.
Every element in one array must use the declared element type. PostgreSQL rejects a value that cannot be converted to that type.
The array itself can also be NULL. This is different from an empty array:
NULLmeans that no array value was supplied or that the value is unknown.- An empty array means that the value is known and contains zero elements.
The following table has a required title and a required array column. If an insert omits tags, PostgreSQL stores an empty text array because of the default.
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);NOT NULL applies to the array column as a whole. It prevents the column from containing NULL, but it does not prevent an array from containing a NULL element. If your application must reject null elements, validate that requirement separately.
Writing Array Values
PostgreSQL supports two common forms for array values.
The ARRAY[...] constructor is usually easiest to read. PostgreSQL infers the array type from the elements or from the target column.
INSERT INTO posts (title, tags) VALUES
('Intro to arrays', ARRAY['sql', 'postgres']),
('Indexing', ARRAY['postgres', 'indexing', 'gin']);The array literal form uses a quoted string with curly braces. Commas separate elements.
INSERT INTO posts (title, tags) VALUES
('Query design', '{sql,queries}'),
('No tags yet', '{}');When an array literal is used outside a context that gives PostgreSQL a type, cast it explicitly:
SELECT '{red,green,blue}'::text[] AS colors;Array literals need special handling when an element contains a comma, a quote, a backslash, or a brace. The ARRAY[...] constructor is often clearer for such values because each element is a normal SQL expression.
INSERT INTO posts (title, tags)
VALUES ('Punctuation', ARRAY['sql,advanced', 'author''s note']);The first value contains a comma as data, not as an element separator. The second value contains an apostrophe escaped according to SQL string rules.
Defaults and Constraints
Choose a default based on the meaning of missing data. Use an empty array when “there are currently no values” is a useful, known state. Leave the column nullable when “the value is not known” has a different meaning.
You can add ordinary constraints to the array column. For example, this table requires a non-null array and limits the number of stored labels:
CREATE TABLE articles (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
labels text[] NOT NULL DEFAULT '{}',
CHECK (cardinality(labels) <= 10)
);The constraint does not make labels unique and does not prevent duplicate elements such as {'sql','sql'}. Decide whether duplicates are meaningful before choosing an array design.
How the Declaration Is Interpreted
The declaration has three separate parts:
text[] determines what each element can contain. NOT NULL determines whether the column itself may be null. DEFAULT '{}' determines what PostgreSQL supplies when an insert does not provide the column.
Arrays are a good fit when the list belongs to exactly one row, is usually read or changed with that row, and does not need independent attributes. If each element needs its own identifier, metadata, permissions, or frequent individual updates, a separate related table is usually easier to constrain and query.
Exercise
In the posts table, what values are stored for tags when an insert omits the column, explicitly supplies NULL, or supplies ARRAY[]::text[]?
Show answer
Omitting the column stores the empty array because of the default. Explicit NULL is rejected because of NOT NULL. ARRAY[]::text[] stores an explicitly typed empty array.