Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Learn how to use array data types in PostgreSQL. Master array slicing, unnesting, ANY/ALL operators, containment (@>), and GIN indexing for fast searches.
Quick answer
PostgreSQL natively supports array data types for scalar columns, such as text[], integer[], or uuid[]. You can slice arrays, expand them into rows with unnest(), search elements with ANY() and ALL(), and accelerate membership lookups using GIN indexes with the containment operator (@>).
FAQs
When should I use an array column instead of a separate junction table?
Use arrays when the list is small (under 50 items), rarely updated individually, and tightly coupled to the parent entity, such as user roles or blog tags.
Does PostgreSQL support multi-dimensional arrays?
Yes. PostgreSQL supports multi-dimensional arrays like integer[][], but all sub-arrays must have matching dimensions.
Can a B-tree index index individual array elements?
No. Standard B-tree indexes only support whole-array equality comparisons. You must use a GIN index to search individual elements with @> or &&.
How do I remove an element from an array in PostgreSQL?
Use the array_remove() function: UPDATE table SET tags = array_remove(tags, 'old_tag') WHERE id = 101.
Build fast text search directly in PostgreSQL without external search engines. Master to_tsvector, to_tsquery, relevance ranking with ts_rank, and GIN indexes.
PostgreSQL treats arrays as first-class citizens. While relational purists argue that multi-valued attributes violate First Normal Form (1NF), real-world applications frequently benefit from storing small lists directly within a row: user notification flags, product tags, or security role permissions.
Using PostgreSQL arrays eliminates the overhead of separate join tables and primary key indexing for small, tightly coupled collections. Understanding array literal syntax, containment operators, and GIN indexing guarantees that array queries remain performant at scale.
Declaring array columns and inserting data
You declare an array column by appending square brackets [] to any valid data type. You can insert arrays using standard SQL array constructors or bracketed string literals.
Declaring and populating array columns
CREATE TABLE engineering_tickets ( ticket_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, title VARCHAR(150) NOT NULL, assigned_tags TEXT[] NOT NULL DEFAULT '{}', sprint_ids INT[] NOT NULL DEFAULT '{}');-- Method 1: Using the ARRAY constructor (recommended for type safety)INSERT INTO engineering_tickets (title, assigned_tags, sprint_ids)VALUES ( 'Fix memory leak in worker', ARRAY['backend', 'performance', 'urgent'], ARRAY[42, 43]);-- Method 2: Using string literal formatINSERT INTO engineering_tickets (title, assigned_tags, sprint_ids)VALUES ( 'Update checkout navigation', '{"frontend", "ui"}', '{43}');
According to the PostgreSQL array documentation, standard PostgreSQL arrays use 1-based indexing by default. An array slice such as assigned_tags[1:2] retrieves the first two elements.
Searching arrays: ANY, ALL, and containment (@>)
Searching for values inside an array requires different operators than standard scalar comparisons:
Querying PostgreSQL array contents
-- Find tickets containing the 'urgent' tag using = ANY()SELECT ticket_id, titleFROM engineering_ticketsWHERE 'urgent' = ANY(assigned_tags);-- Find tickets that contain BOTH 'backend' AND 'performance' (containment operator)SELECT ticket_id, titleFROM engineering_ticketsWHERE assigned_tags @> ARRAY['backend', 'performance'];-- Find tickets that overlap with ANY tag in a candidate list (overlap operator &&)SELECT ticket_id, titleFROM engineering_ticketsWHERE assigned_tags && ARRAY['urgent', 'critical', 'blocker'];
The @> operator checks if the left array contains every element of the right array. The && operator checks if the two arrays have at least one element in common.
Expanding and aggregating arrays: unnest() and array_agg()
When you need to normalize array data for reporting or joins, unnest() expands array elements into individual relational rows. Conversely, array_agg() collapses multiple rows into a single array.
Unnesting and aggregating array values
-- Expand tags into rows to calculate tag frequencySELECT unnest(assigned_tags) AS tag, COUNT(*) AS ticket_countFROM engineering_ticketsGROUP BY tagORDER BY ticket_count DESC;-- Aggregate rows into an arraySELECT author_id, array_agg(title ORDER BY created_at DESC) AS recent_ticket_titlesFROM engineering_ticketsGROUP BY author_id;
Indexing array columns with GIN
Standard B-tree indexes cannot index individual elements inside an array column. A B-tree index on assigned_tags can evaluate exact array equality (WHERE assigned_tags = ARRAY['a', 'b']), but it cannot accelerate containment (@>) or overlap (&&) searches. Check our guide on PostgreSQL JSONB indexing for related GIN mechanics.
To make array membership queries fast, create a Generalized Inverted Index (GIN). A GIN index creates an internal B-tree where each unique array element points to a posting list of matching heap row pointers.
Creating a GIN index on an array column
-- Create GIN index for fast containment and overlap queriesCREATE INDEX idx_tickets_tags_ginON engineering_tickets USING gin (assigned_tags);-- This query now uses a Bitmap Index Scan on idx_tickets_tags_gin:EXPLAIN (COSTS OFF)SELECT title FROM engineering_ticketsWHERE assigned_tags @> ARRAY['urgent'];
As outlined in the PostgreSQL GIN indexing documentation, GIN indexes speed up array lookups significantly, but incur higher write overhead during inserts and updates compared to standard B-trees.
Actionable checklist for PostgreSQL array usage
Verify relationship cardinality: use arrays for small, bounded lists (tags, roles); use junction tables for high-cardinality relationships.
Use 1-based index offsets: remember that PostgreSQL array indexing begins at 1, not 0.
Add GIN indexes: create GIN indexes when queries frequently filter with @> or && operators.
Avoid frequent in-place updates: modifying array elements rewrites the entire row and updates the GIN index postings list.
Prefer ARRAY constructor: use ARRAY['val1', 'val2'] over string literals to prevent escaping errors with quotes.
Enforce array dimensions: write CHECK constraints on array length if your business domain limits element count.
Wrapping up
PostgreSQL arrays provide a clean, high-performance way to store and query multi-valued attributes without normalizing into junction tables. Combining containment operators with GIN indexes yields sub-millisecond lookups on millions of records. Format your array schemas and queries cleanly by running them through sqlfmt before deployment.