PostgreSQL
Array Operations
Store and query arrays of scalar values.
By EZ4Code Team
arraydatatypegin
Code
-- Create table with array column
CREATE TABLE posts (
id serial PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);
-- Insert and query
INSERT INTO posts(title, tags) VALUES ('Hello', ARRAY['postgres','db']);
INSERT INTO posts(title, tags) VALUES ('World', '{"news","db"}');
-- Containment, overlap, and indexing
SELECT * FROM posts WHERE tags @> ARRAY['db'];
SELECT * FROM posts WHERE tags && ARRAY['news'];
SELECT unnest(tags) AS tag FROM posts WHERE id = 1;
-- Update and append
UPDATE posts SET tags = array_append(tags, 'tutorial') WHERE id = 1;
-- GIN index for fast array membership
CREATE INDEX idx_posts_tags ON posts USING gin(tags);Explanation
PostgreSQL arrays let you store multiple values in one column, useful for tags or one-to-many relationships that don't need a join table. Operators like @> (contains) and && (overlap) test array contents, accelerated by a GIN index. unnest expands an array into rows for further processing.
More PostgreSQL Snippets
SELECT with JOINs
Use INNER, LEFT, and LATERAL joins in PostgreSQL.
JSONB Operations
Store, query, and index JSONB documents.
Window Functions
Compute rankings, running totals, and moving averages.
Common Table Expressions
Use CTEs and recursive CTEs for readable queries.
Index Types
Create B-tree, GIN, GiST, and partial indexes.
Full-Text Search
Search text using tsvector, tsquery, and ranking.