Arrays in PostgreSQL
From the PostgreSQL Advanced Features cheat sheet · PostgreSQL Data Types · verified Jul 2026
Arrays
Store multiple values in a single column
sql
-- Create table with arrays
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name TEXT,
tags TEXT[], -- Array of text
prices INTEGER[] -- Array of integers
);
-- Insert arrays
INSERT INTO products (name, tags, prices) VALUES
('Laptop', ARRAY['electronics', 'computers'], ARRAY[999, 1299]),
('Book', '{"education", "programming"}', '{15, 20, 25}');
-- Query arrays
SELECT * FROM products
WHERE 'electronics' = ANY(tags); -- Contains value
SELECT * FROM products
WHERE tags @> ARRAY['computers']; -- Contains all
-- DETAILED_TAB:
-- Array operations
SELECT
array_length(tags, 1), -- Array length
tags[1], -- First element (1-indexed!)
array_append(tags, 'new'), -- Add element
array_remove(tags, 'old'), -- Remove element
unnest(tags) -- Expand to rows
FROM products;
-- Array aggregation
SELECT
category,
array_agg(DISTINCT tag) AS all_tags
FROM product_tags
GROUP BY category;💡 Arrays are 1-indexed in PostgreSQL, not 0-indexed
📌 Use ANY() and ALL() for array comparisons
⚡ Arrays can hurt performance if overused
⚠️ Consider normalization for complex array queries
🔗 Related: unnest() to convert array to rows
arraysdatatypes