Sub topic 11
Arrays in PostgreSQL
Assume you can create tables and run SELECT and INSERT statements. An array is a single column value that contains multiple values of one PostgreSQL type. Arrays are useful for small, naturally grouped lists, such as product tags or a user's preferred languages.
Declaring and storing arrays
Add [] to a base type to declare an array type. For example, text[] stores an array of text values, and integer[] stores an array of integers.
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
tags text[] NOT NULL DEFAULT '{}',
related_ids bigint[]
);
INSERT INTO products (name, tags, related_ids)
VALUES
('Keyboard', ARRAY['input', 'hardware'], ARRAY[2, 3]),
('Monitor', '{"display", "hardware"}', NULL);
SELECT name, tags
FROM products;PostgreSQL supports both the ARRAY[...] constructor and an array literal such as '{"display","hardware"}'. The constructor is usually easier to read and avoids some quoting problems.
Array indexes start at 1, not 0.
SELECT
tags[1] AS first_tag,
tags[2] AS second_tag
FROM products
WHERE name = 'Keyboard';An index outside the array's bounds returns NULL. A NULL array is different from an empty array. A NULL value means the list is unknown or not supplied. An empty array means the list is known to contain no elements.
Searching and expanding arrays
The @> operator tests whether the left array contains every element in the right array. The && operator tests whether two arrays overlap.
SELECT name
FROM products
WHERE tags @> ARRAY['hardware'];
SELECT name
FROM products
WHERE tags && ARRAY['display', 'input'];The ANY construct compares a value with each array element.
SELECT name
FROM products
WHERE 'input' = ANY(tags);Use unnest when a query needs one result row per element. This is useful for reporting and joins.
SELECT
p.name,
tag
FROM products AS p
CROSS JOIN LATERAL unnest(p.tags) AS tag
ORDER BY p.name, tag;Indexes and schema decisions
A GIN index can accelerate common containment and overlap queries.
CREATE INDEX products_tags_gin_idx
ON products USING gin (tags);Arrays are a good fit when the list belongs to one row, has a simple element type, and does not need independent attributes. They become awkward when each element needs its own identity, constraints, metadata, or frequent updates. In those cases, use a related table instead.
| Use an array when | Use a related table when |
|---|---|
| The list is small and simple | Elements need their own columns |
| The values are read with their parent row | You frequently search, update, or aggregate elements |
| Element order or grouping belongs to the value | Each element needs foreign keys or uniqueness rules |
An array does not automatically enforce uniqueness. For example, ARRAY['sql', 'sql'] is valid. Add application checks, a database function, or a normalized table if duplicate elements are invalid.
Exercise
What does tags && ARRAY['api', 'web'] test?
Show answer
It tests whether tags shares at least one element with api or web.