Sub topic 3
Reading elements and slices with 1-based subscripts
This chapter covers how to pull one element or a range of elements out of an array value. It also covers the cases that surprise people coming from other languages: positions start at 1, out-of-range reads return NULL instead of failing, and a slice is always an array.
I assume you can write basic SELECT queries and know how three-valued logic treats NULL. I also assume you have met text[] columns and the ARRAY[...] and '{...}' literal forms from the earlier chapters.
The sample data
The examples use the posts table from earlier in this tutorial. If you don't have it, run this setup.
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}');Then add a third row with no tags, so you can see how empty arrays behave:
INSERT INTO posts (title) VALUES ('Empty');The DEFAULT '{}' gives the new row an empty array, not NULL.
Single elements: array[n]
To read one element, put an integer position in square brackets after the array expression. PostgreSQL counts from 1, so tags[1] is the first tag.
SELECT title, tags[1] AS first_tag, tags[3] AS third_tag
FROM posts
ORDER BY id; title | first_tag | third_tag
-----------------+-----------+-----------
Intro to arrays | sql |
Indexing | postgres | gin
Empty | |
(3 rows)psql shows NULL as a blank cell. The first row has only two tags, so tags[3] is NULL. It is not an error.
A single subscript returns the element type. For a text[] column, tags[1] is a text value. You can compare it, concatenate it, or pass it to a function like any other text:
SELECT title FROM posts WHERE tags[1] = 'postgres';The subscript can be any integer expression. That includes a column, a query parameter, or a function call:
SELECT title, tags[array_length(tags, 1)] AS last_tag
FROM posts
ORDER BY id;array_length(tags, 1) is the number of elements along dimension 1, so this expression returns the last element. For the empty array it returns NULL, so last_tag is NULL there too. A cardinality(tags) subscript would give tags[0], which is also NULL, so both forms are safe on empty arrays.
What happens when the position does not exist
A read with an out-of-range position returns NULL. This applies to a position past the end, to 0, and to negative numbers. PostgreSQL never raises an error for a read, and it has no "count from the end" convention like Python's -1.
The flowchart shows the full decision for one subscript expression.
The consequence is that a NULL result has three possible meanings:
- The array itself is
NULL. - The position is outside the array.
- The element at that position is
NULL.
If the difference matters, check the length with cardinality(tags), or test tags IS NULL, before trusting the result.
Slices: array[from:to]
A slice uses a colon between two positions. Both ends are inclusive, and the result is an array of the same type as the original.
SELECT title,
tags[1] AS first_tag,
tags[2:3] AS second_and_third
FROM posts
ORDER BY id; title | first_tag | second_and_third
-----------------+-----------+------------------
Intro to arrays | sql | {postgres}
Indexing | postgres | {indexing,gin}
Empty | | {}
(3 rows)The first post has only two tags, so tags[2:3] returns the part that exists, {postgres}. The empty array returns the empty array {}. A slice never fails because it reaches past the end.
You can leave out either bound to mean "from the start" or "to the end". Leaving out both returns the whole array.
The next query shows every case on one four-element array:
WITH t(a) AS (SELECT ARRAY[10, 20, 30, 40])
SELECT a[1] AS first_el,
a[4] AS last_el,
a[5] AS past_end,
a[0] AS zero,
a[-1] AS negative,
a[2:3] AS middle,
a[:2] AS head,
a[3:] AS tail,
a[:] AS whole,
a[3:9] AS clipped,
a[6:9] AS outside,
a[3:2] AS reversed
FROM t;| Expression | Result | Reason |
|---|---|---|
| `a[1]` | `10` | Positions start at 1. |
| `a[4]` | `40` | The last valid position equals the length. |
| `a[5]` | `NULL` | Past the end, no error. |
| `a[0]` | `NULL` | Position 0 does not exist. |
| `a[-1]` | `NULL` | Negative positions do not count from the end. |
| `a[2:3]` | `{20,30}` | Both bounds are inclusive. |
| `a[:2]` | `{10,20}` | Omitted lower bound means the first position. |
| `a[3:]` | `{30,40}` | Omitted upper bound means the last position. |
| `a[:]` | `{10,20,30,40}` | Both omitted returns a copy of the whole array. |
| `a[3:9]` | `{30,40}` | The slice is clipped to the existing elements. |
| `a[6:9]` | `{}` | No overlap returns an empty array, not `NULL`. |
| `a[3:2]` | `{}` | A lower bound above the upper bound returns an empty array. |
Single-element reads and slices fail differently, and that difference decides how you write fallback logic:
- A single-element read outside the array gives
NULL. - A slice with no overlap gives an empty array.
A slice of one element is still an array
tags[1:1] and tags[1] look similar, but they have different types:
SELECT tags[1] AS element, -- text
tags[1:1] AS slice -- text[], for example {sql}
FROM posts
WHERE id = 1;Comparing the slice to a plain string is a mistake. In WHERE tags[1:1] = 'sql', PostgreSQL tries to read 'sql' as an array literal and fails with a "malformed array literal" error. Compare against ARRAY['sql'] instead, or use the single subscript tags[1] = 'sql'.
Slices are renumbered from 1
A slice is a new array, and its positions start at 1 no matter where it began in the original:
SELECT (ARRAY[10, 20, 30, 40])[3:4] AS slice,
(ARRAY[10, 20, 30, 40])[3:4][1] AS wrong_idea;The second expression looks like "the first element of the slice" but is not valid for a one-dimensional array. Once any bracket pair is a slice, PostgreSQL treats every bracket pair on that expression as a slice. To get the first element of a slice, wrap the slice in parentheses:
SELECT ((ARRAY[10, 20, 30, 40])[3:4])[1] AS first_of_slice; -- 30Subscripting expressions needs parentheses
You can subscript a column name directly, with or without a table qualifier: tags[1] or posts.tags[1]. For any other expression, such as a function call, a cast, or a literal, the expression must be in parentheses.
-- Syntax error:
-- SELECT string_to_array('a,b,c', ',')[2];
SELECT (string_to_array('a,b,c', ','))[2]; -- b
SELECT (ARRAY['x', 'y', 'z'])[2:3]; -- {y,z}
SELECT ('{1,2,3}'::int[])[1]; -- 1The parentheses tell the parser that the brackets belong to the array expression and are not part of a type name such as int[].
Arrays that do not start at 1
The 1-based rule is a default and not a fixed property of the type. A literal can carry explicit bounds in front of the braces:
SELECT ('[0:2]={10,20,30}'::int[])[0] AS zero_based_first,
array_lower('[0:2]={10,20,30}'::int[], 1) AS lower_bound,
array_upper('[0:2]={10,20,30}'::int[], 1) AS upper_bound;This returns 10, 0, and 2. Reading such an array with [1] gives the second element, which is 20.
Arrays built by ARRAY[...], array_agg, unnest-based queries, and slices all start at 1. Non-default bounds mostly appear if you write them by hand or assign to a position far outside an existing array in an UPDATE. The next chapter covers assignment. In application code that reads arrays, array_lower(arr, 1) and array_upper(arr, 1) give the real bounds if you cannot assume they start at 1.
Subscripts in filters and indexes
You can use a subscript in a WHERE clause, as in WHERE tags[1] = 'postgres'. That condition asks about a specific position. A GIN index on tags does not support it, because GIN indexes answer "which rows contain this value anywhere". The @>, &&, and ANY operators are the ones to use for that question, and the search chapter covers them.
If you really do filter on a fixed position often, you can build an expression index on that subscript:
CREATE INDEX posts_first_tag_idx ON posts ((tags[1]));The extra parentheses are required because the indexed item is an expression and not a plain column. Before building such an index, ask whether the first element is meaningful in your data. If the position carries a meaning, such as "the primary tag", a separate column often models it more clearly.
Common mistakes
- Counting from 0.
tags[0]returnsNULL, andtags[1]is the first element. - Expecting an error on a bad position. Out-of-range reads return
NULLand out-of-range slices return a shorter or empty array. - Using a negative position to reach the end. Use
arr[cardinality(arr)]orarr[array_upper(arr, 1)]. - Comparing a slice to a scalar. A slice is an array, even when it holds one element.
- Forgetting parentheses around a function call or cast before the brackets.
- Treating position as identity. Positions shift when elements are added or removed, so a stored
tags[2]may refer to a different element later.
Exercise
Table posts has a tags text[] column. Write a query that returns each post's title together with its last tag, and explain what the query returns for a post whose tags is '{}'.
Show answer
SELECT title, tags[cardinality(tags)] AS lasttag FROM posts; For a post with tags = '{}', cardinality(tags) is 0, so the subscript is tags[0]. Position 0 is outside the array, so the read returns NULL and no error is raised. (tags[arraylength(tags, 1)] also works: array_length of an empty array is NULL, and a NULL subscript yields NULL.)
Exercise
Given a = ARRAY[5, 6, 7, 8, 9], give the result of each expression: a[2], a[6], a[-1], a[2:4], a[4:], a[7:9], and a[1:1] = ARRAY[5].
Show answer
a[2] is 6. a[6] is NULL (past the end). a[-1] is NULL (negative positions do not count from the end). a[2:4] is {6,7,8}. a[4:] is {8,9}. a[7:9] is {} (a slice with no overlap is an empty array, not NULL). a[1:1] = ARRAY[5] is true, because a[1:1] is the one-element array {5}.
Exercise
Why does SELECT string_to_array('a,b,c', ',')[2]; fail, and what is the corrected query?
Show answer
A subscript can follow a column name directly, but any other expression, including a function call, must be wrapped in parentheses so the parser knows the brackets subscript the result. The corrected query is SELECT (stringtoarray('a,b,c', ','))[2]; and it returns b.