AI Hints
PostgreSQL · Lesson 37 of 120

Arrays

Lists in a column.

⏱ 2 min read▶ Video at 32:13🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Each book has a few tags, like twist, or series. Instead of a separate table, Postgres can store a list right in a column. That's an array.

  • A few tags
  • No extra table
  • text[]

Tags as an array

The tags column has type text array. Curly braces show the list. Square brackets pick one item, and arrays start at one, not zero. Run it. Each book's tags, and its first tag.

query.sqlsql
SELECT title, tags, tags[1] AS first_tag
FROM books
ORDER BY book_id
LIMIT 4;
Output
          title           |        tags        | first_tag
--------------------------+--------------------+-----------
 The Silent Orchard       | {series,twist}     | series
 Code of the River        | {twist,fast-paced} | twist
 Stars Over Lagos         | {series,love}      | series
 A Short History of Bread | {empire,biography} | empire
(4 rows)

Arrays in your own table

Array literals go in curly braces, inside quotes. Or use the array constructor with square brackets. Cardinality counts the items. Run it. Two reading lists, and their sizes.

query.sqlsql
CREATE TABLE reading_lists (name text, book_ids integer[]);
INSERT INTO reading_lists VALUES
  ('Summer', '{3, 7, 12}'),
  ('Weekend', ARRAY[2, 5]);
SELECT name, book_ids, cardinality(book_ids) AS books FROM reading_lists;
Output
CREATE TABLE
INSERT 0 2
  name   | book_ids | books
---------+----------+-------
 Summer  | {3,7,12} |     3
 Weekend | {2,5}    |     2
(2 rows)
Also uses _empty
1

Summary

Arrays store lists in a column, using curly braces, and start counting at one. Next, searching inside arrays.

Key takeaways
  • text[]
  • {a, b}
  • Index from 1
Next up: Array Operators — search inside lists