Sub topic 2
Writing array values: `ARRAY[...]` and `'{...}'`
This chapter assumes that you know basic INSERT statements, PostgreSQL data types, and the difference between NULL and an empty value. PostgreSQL arrays store multiple values of one element type in a single column. For example, a text[] column stores an array whose elements are all text values.
Declare an array column
Add square brackets to a PostgreSQL type name to declare an array of that type:
CREATE TEMP TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);The tags column has type text[]. Its default value is an empty text array, written as '{}'. The NOT NULL constraint means that a row must contain an array, even if that array contains no elements.
An empty array and NULL have different meanings:
- An empty array means that the row has a known list with no values.
NULLmeans that no list is available or the value is unknown.
Use the `ARRAY[...]` constructor
The ARRAY[...] constructor is usually the clearest way to write an array. Put each element between the square brackets and separate elements with commas.
INSERT INTO posts (title, tags) VALUES
('Intro to arrays', ARRAY['sql', 'postgres']),
('Indexing', ARRAY['postgres', 'indexing', 'gin']);PostgreSQL infers the element type from the values. In this example, the strings make each value a text element, so the complete expressions have type text[].
You can also write an array of numbers:
SELECT ARRAY[10, 20, 30] AS scores;If PostgreSQL cannot infer the type, add an explicit cast. An empty constructor has no elements from which to infer a type:
SELECT ARRAY[]::text[] AS no_tags;
SELECT ARRAY[]::integer[] AS no_scores;The cast uses :: followed by the target type. It tells PostgreSQL how to interpret the value.
Use the array literal form
PostgreSQL also accepts a string that follows its array input format. The string begins with { and ends with }:
INSERT INTO posts (title, tags) VALUES
('Literal syntax', '{postgres,arrays,sql}');The column type tells PostgreSQL to interpret the string as a text[], not as ordinary text. You can make the type explicit when needed:
SELECT '{postgres,arrays}'::text[] AS tags;
SELECT '{}'::text[] AS empty_tags;The two forms create equivalent arrays:
SELECT
ARRAY['sql', 'postgres'] AS constructor_value,
'{sql,postgres}'::text[] AS literal_value;The constructor is often easier to read because each element is a normal SQL expression. The literal form is useful when importing or formatting PostgreSQL array values as text.
Quote elements in array literals
Array literals use commas and braces as syntax. If an element contains one of those characters, whitespace that must be preserved, or a double quote, quote the element inside the literal.
SELECT '{"SQL basics","PostgreSQL, advanced","say ""hello"""}'::text[];This array has three elements:
SQL basicsPostgreSQL, advancedsay "hello"
The comma inside PostgreSQL, advanced is part of the element because the element is quoted. A double quote inside a quoted element is represented by two double quotes.
With the constructor, the same values are usually easier to write:
SELECT ARRAY[
'SQL basics',
'PostgreSQL, advanced',
'say "hello"'
]::text[];The constructor accepts ordinary SQL string expressions, so its quoting rules are separate from the array literal's parsing rules.
Keep element types consistent
An array has one element type. PostgreSQL can sometimes convert compatible values, but unrelated values require an explicit choice or produce an error.
SELECT ARRAY[1, 2, 3]::integer[] AS numbers;
SELECT ARRAY['1', '2', '3']::text[] AS labels;For multidimensional arrays, nested constructors must have compatible dimensions:
SELECT ARRAY[
ARRAY[1, 2],
ARRAY[3, 4]
]::integer[][];Each nested array has two elements, so PostgreSQL can form a rectangular two-dimensional array. Arrays are not a substitute for unrelated values with different types.
> callout note > Prefer ARRAY[...] when writing SQL by hand. Use the brace-delimited form when exchanging values with PostgreSQL's array text format. Cast empty arrays explicitly so the element type is unambiguous.
Exercise
Write an INSERT statement that adds a post titled Data types with the tags sql, postgres, and types using the brace-delimited array literal form.
Show answer
INSERT INTO posts (title, tags) VALUES ('Data types', '{sql,postgres,types}');