Sub topic 2
Writing array values: ARRAY[...] and '{...}'
This chapter covers the two ways to write an array value in PostgreSQL. It assumes you know basic SELECT, INSERT, and UPDATE, can create a table with typed columns, and can run statements in psql. It also assumes you know that a NULL in SQL means "unknown", not "empty". You don't need to have used arrays before. Reading elements, searching, and indexing come in later chapters.
Two syntaxes for one value
PostgreSQL gives you two ways to write an array value:
- The ARRAY constructor is an SQL expression:
ARRAY['sql', 'postgres']. Each element is a normal expression, so it can be a literal, a column, a function call, or arithmetic. - The array literal is a single quoted string in PostgreSQL's array text format:
'{sql,postgres}'. The server parses the string and converts it to the target array type.
Both produce the same kind of value. Start with a table that stores tags as a text[] column and fill it using each form:
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);
INSERT INTO posts (title, tags) VALUES
('Intro to arrays', ARRAY['sql', 'postgres']),
('Indexing', '{postgres,indexing,gin}');The first row uses the constructor and the second uses the literal. The default '{}' is an empty array, which later sections explain.
The ARRAY constructor
Write the keyword ARRAY, then a comma-separated list of expressions in square brackets:
SELECT ARRAY[1, 2, 3] AS ints,
ARRAY['a', 'b'] AS words,
ARRAY[1 + 1, length('abc')] AS computed;The result is {1,2,3}, {a,b}, and {2,3}. The third column shows the main advantage of the constructor. The elements are expressions, so you can use column values:
SELECT ARRAY[title, 'draft'] AS label_pair
FROM posts;Because the elements are ordinary SQL expressions, you quote strings the usual SQL way, with single quotes. You never have to think about array-specific escaping.
How the element type is chosen
You don't declare a type in the constructor. PostgreSQL infers it from the elements, using the same rules as UNION or CASE. You can check the result with pg_typeof:
SELECT pg_typeof(ARRAY[1, 2]) AS all_ints,
pg_typeof(ARRAY[1, 2.5]) AS int_and_decimal,
pg_typeof(ARRAY['a', 'b']) AS strings;This returns integer[], numeric[], and text[]. When integers and decimals are mixed, the array gets the type both can convert to, which is numeric. Quoted values with no other type information are resolved to text.
Mixing types that have no common type fails:
SELECT ARRAY[1, 'x'];PostgreSQL tries to read 'x' as an integer and reports invalid input syntax for type integer: "x". The fix is to make the elements agree, for example by writing ARRAY['1', 'x'].
Casting the whole array
Append ::type[] to convert an array. The conversion is applied to each element:
SELECT ARRAY['1', '2', '3']::int[] AS parsed,
ARRAY[1, 2, 3]::text[] AS as_text;Casting is also how you fix the type when inference gives the wrong answer. ARRAY[1, 2] is integer[], but if the column is bigint[] you can write ARRAY[1, 2]::bigint[]. On INSERT and UPDATE PostgreSQL usually converts the value to the column type for you.
The array literal
An array literal is a string that follows this shape:
'{ element, element, ... }'Curly braces surround the elements, and commas separate them. Because the value is just a string, PostgreSQL has to learn the element type from context. In an INSERT into a text[] column, the column supplies it. In a bare SELECT, you add a cast:
SELECT '{1,2,3}'::int[] AS ints,
'{2026-01-01,2026-02-01}'::date[] AS dates,
'{sql,postgres}'::text[] AS words;Inside the braces, elements are not SQL expressions. Writing '{1+1}'::int[] fails because 1+1 is not an integer. Writing '{abc}'::text[] works with no inner quotes, because the text format has its own quoting rules.
Whitespace
Unquoted elements lose any leading and trailing whitespace. Whitespace between words is kept:
SELECT '{ a , b ,hello world }'::text[];The output is {a,b,"hello world"}. The printed form adds double quotes around the last element because it contains a space.
Quoting elements inside a literal
Wrap an element in double quotes when it contains characters that the array parser treats specially. This is where most literal-writing mistakes happen:
| Element contains | Example element | How to write it in the literal |
|---|---|---|
| A comma | `a,b` | `"a,b"` |
| Curly braces | `{x}` | `"{x}"` |
| A double quote | `say "hi"` | `"say \"hi\""` |
| A backslash | `a\b` | `"a\\b"` |
| Leading or trailing spaces | ` padded ` | `" padded "` |
| Nothing (empty string) | (empty) | `""` |
| The word NULL, as text | `NULL` | `"NULL"` |
Inside double quotes, a backslash escapes the next character. This applies to double quotes and to backslashes. Putting several of these together:
SELECT '{"hello world", "a,b", "say \"hi\"", ""}'::text[] AS tricky;The result is {"hello world","a,b","say \"hi\"",""}. It has four elements, and the last one is an empty string.
The backslash handling in the table assumes the setting standard_conforming_strings is on, which is the default. In that mode, the SQL string '...' passes backslashes through unchanged, so the array parser sees them. If the setting is off, or you use an E'...' string, the SQL layer processes backslashes first and you need to double them again. When you are unsure, use the ARRAY constructor and skip all of this.
Output uses the same format
When PostgreSQL prints an array, it uses the literal syntax and adds quotes only where needed. That means a value you copy from psql output can be pasted back as a literal. It also explains why ARRAY['a', 'NULL'] prints as {a,"NULL"}. The quotes mark the second element as the text string NULL and not as a missing value.
Choosing between the two forms
In practice:
- Use the constructor in hand-written SQL, in queries that build arrays from other values, and whenever the data contains characters that need quoting.
- Use the literal when a client library sends an array as one parameter, or when you paste a value from
psqloutput, a dump, or a CSV.
A prepared statement shows the second case. The parameter is declared as text[], and the client sends the literal as text:
PREPARE posts_with_all_tags (text[]) AS
SELECT title FROM posts WHERE tags @> $1;
EXECUTE posts_with_all_tags('{postgres,gin}');The @> operator in this example is covered in the chapter on filtering rows. Here, the point is that '{postgres,gin}' is converted to text[] because the parameter was declared with that type. Most drivers can send native arrays and do this conversion for you. If yours does not, build the literal string in application code and pass it as a single parameter with an explicit ::text[] cast. Never splice it into the SQL text yourself.
NULL elements
Both syntaxes allow NULL as an element. In a constructor it is the ordinary keyword. In a literal it is the bare word NULL, in any letter case:
SELECT ARRAY[1, NULL, 3] AS from_constructor,
'{1,NULL,3}'::int[] AS from_literal,
'{"NULL"}'::text[] AS the_string_null;The first two are the same array, {1,NULL,3}, with a missing value in position 2. The third is an array holding the four-letter string NULL. The only difference is the quotes.
A bare ARRAY[NULL, NULL] has no type information at all. PostgreSQL falls back to text[]. If you need a different element type, cast it: ARRAY[NULL, NULL]::int[].
Don't confuse a NULL element with a NULL array. The column tags text[] NOT NULL rejects a missing array but accepts {a,NULL}. The chapter on NULLs and empty arrays covers how these behave in comparisons.
Empty arrays
An empty array has no elements. In a literal it is '{}', which needs a cast unless context provides the type. The constructor needs one in every case, because there are no elements to infer a type from:
SELECT '{}'::text[] AS from_literal,
ARRAY[]::text[] AS from_constructor;Writing ARRAY[] alone fails with cannot determine type of empty array. The error message tells you what to do. Add a cast such as ARRAY[]::text[], or write '{}'::text[].
An empty array is different from NULL. The default '{}' in the posts table means "no tags", and NOT NULL ensures every row has an array to work with.
Multidimensional values
Nest brackets or braces to write a two-dimensional array:
SELECT ARRAY[[1, 2], [3, 4]] AS from_constructor,
'{{1,2},{3,4}}'::int[] AS from_literal;Both give {{1,2},{3,4}}. Every inner array at the same level must have the same length. A ragged value such as '{{1,2},{3}}'::int[] or ARRAY[[1,2],[3]] raises an error. Reading and limits of these arrays are covered later in the tutorial.
Common errors
- Forgetting the cast on a bare literal.
SELECT '{1,2,3}'returns text, not an array. Add::int[]. - Using double quotes for strings in the constructor.
ARRAY["a"]refers to a column nameda. Elements in the constructor use single quotes. - Using single quotes inside the braces. In
'{'a','b'}'the quotes end the SQL string early. In a literal, strings are bare or double-quoted:'{a,b}'. - Unquoted commas in element text.
'{New York, NY}'is two elements,New YorkandNY. Write'{"New York, NY"}'. - Mismatched nested lengths. Every inner array must have the same number of elements.
- An empty constructor with no cast.
ARRAY[]needs::type[].
Exercise
Write one INSERT into posts that adds a row titled 'Quoting' with exactly three tags: the string a,b, the string NULL, and a missing value (a real NULL). Do it once with the ARRAY constructor and once with an array literal. What does the literal look like when PostgreSQL prints the stored array?
Show answer
Constructor: INSERT INTO posts (title, tags) VALUES ('Quoting', ARRAY['a,b', 'NULL', NULL]); Literal: INSERT INTO posts (title, tags) VALUES ('Quoting', '{"a,b","NULL",NULL}'); In the literal, the comma string and the string NULL need double quotes, and the bare NULL is the missing value. The stored array prints as {"a,b","NULL",NULL}. The quotes around "NULL" distinguish the text string from the real NULL.
Exercise
Each statement below fails. Say why and fix it. (1) SELECT ARRAY[]; (2) SELECT ARRAY[1, 'two']; (3) SELECT '{{1,2},{3}}'::int[];
Show answer
(1) PostgreSQL cannot infer an element type from zero elements. Write ARRAY[]::int[] (or any other type). (2) 'two' cannot be converted to an integer, so the elements have no common type. Use ARRAY['1', 'two'] to get text[], or ARRAY[1, 2]. (3) The inner arrays have different lengths (2 and 1), and multidimensional arrays must be rectangular. Use '{{1,2},{3,4}}'::int[].