</>
Skip to content
PostgreSQL lessons (32/38)

PostgreSQL — Arrays

Array Data Type

CREATE TABLE products (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    tags TEXT[]
);

INSERT INTO products (name, tags) 
VALUES ('Phone', ARRAY['electronics', 'mobile']);

Query Arrays

-- Check membership
SELECT * FROM products WHERE 'electronics' = ANY(tags);

-- Array contains
SELECT * FROM products WHERE tags @> ARRAY['mobile'];

-- Array length
SELECT array_length(tags, 1) FROM products;

Array Functions

FunctionDescription
array_appendAdd element
array_removeRemove element
array_lengthGet length
array_catConcatenate
unnestExpand to rows

Manipulate Arrays

-- Append
UPDATE products SET tags = array_append(tags, 'new') WHERE id = 1;

-- Remove
UPDATE products SET tags = array_remove(tags, 'old') WHERE id = 1;

-- Concatenate
UPDATE products SET tags = tags || ARRAY['extra'] WHERE id = 1;

Index Arrays

CREATE INDEX idx_tags ON products USING GIN (tags);

Mini Practice

  1. Create array column
  2. Query arrays
  3. Manipulate arrays
  4. Index arrays

Up Next

Continue with Extensions — PostgreSQL extensions.

Related Topics

Frequently Asked Questions about Arrays

What is Arrays in PostgreSQL?

Arrays is a fundamental concept in PostgreSQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Arrays?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Arrays.

Why is Arrays important in PostgreSQL?

Arrays is essential for PostgreSQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.