Sub topic 1
Declaring Array Columns in PostgreSQL
This chapter assumes you can write basic SQL and create tables. Array columns hold several values of one type in a single cell, so they can replace a separate table for small, simple lists.
Prerequisites
You should know CREATE TABLE, INSERT, and SELECT, and you should be able to run queries in psql or another PostgreSQL client. You should also understand how NULL behaves in a WHERE clause.
Declaring array columns
Add [] after any base type to make an array type. text[] holds text values, and integer[] holds integers. The following table defines a tags column that stores text values and defaults to an empty array:
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);The DEFAULT '{}' clause means a new row gets an empty array unless you provide a value. This avoids NULL tags in rows where you have no tags.
Writing array values: ARRAY[...] and '{...}'
PostgreSQL accepts two forms. The ARRAY constructor takes a list of values in square brackets. The literal form wraps comma-separated values in braces and quotes the whole string:
INSERT INTO posts (title, tags) VALUES
('Intro to arrays', ARRAY['sql', 'postgres']),
('Indexing', '{postgres,indexing,gin}');Both forms produce the same text[] value. The brace form is convenient for pasting data, but the constructor is clearer when values come from expressions.
Reading elements and slices with 1-based subscripts
Array positions start at 1, not 0. A slice such as [2:3] returns a smaller array:
SELECT title,
tags[1] AS first_tag,
tags[2:3] AS second_and_third
FROM posts;A position past the end returns NULL, not an error. A slice past the end returns the part that exists.
> Note: Subscripts are 1-based even though many languages count from 0.
Exercise
Exercise
For a row where tags is '{}', what does tags[1] return?
Show answer
It returns NULL. The array has no element at position 1, and PostgreSQL returns NULL for an out-of-range subscript instead of raising an error.