CREATE TABLE posts ( id bigserial PRIMARY KEY, tags text[] NOT NULL DEFAULT '{}', scores int[][] -- multidimensional);
Syntax
Meaning
type[]
1-D array of any type
type[3]
Size annotation (not enforced)
type[][]
Multi-dim (rectangular)
2. Inserting Array Data
INSERT INTO posts(tags) VALUES (ARRAY['sql','perf']);INSERT INTO posts(tags) VALUES ('{"intro","first"}');
3. Accessing Array Elements
SELECT tags[1], tags[array_length(tags,1)] FROM posts;
Detail
Note
Indexing
1-based
Out-of-bounds
Returns NULL
4. Updating Array Elements
UPDATE posts SET tags[1] = 'lead' WHERE id = 1;UPDATE posts SET tags = tags || 'extra' WHERE id = 1;UPDATE posts SET tags = array_remove(tags, 'old') WHERE id = 1;
5. Querying Array Contents
SELECT * FROM posts WHERE 'sql' = ANY(tags);SELECT * FROM posts WHERE tags @> ARRAY['sql','perf']; -- contains allSELECT * FROM posts WHERE tags && ARRAY['sql','db']; -- overlap