Arrays

Arrays

Syntax

column_name DATATYPE[] {CONSTRAINT}
CREATE TABLE table_array
(
    id     SERIAL,
    name   varchar(100),
    grades text[]
);

INSERT INTO table_array (name, grades)
VALUES ('person 1', array ['100','45']);
INSERT INTO table_array (name, grades)
VALUES ('person 2', array ['100','90']);
INSERT INTO table_array (name, grades)
VALUES ('person 3', array ['100','97']);
INSERT INTO table_array (name, grades)
VALUES ('person 4', array ['100','94']);


SELECT name, grades[1]
FROM table_array;

   name   | grades 
----------+--------
 person 1 | 100
 person 2 | 100
 person 3 | 100
 person 4 | 100

Array in Tables

Insert

  • for non text data , use {value1,value2} or array ['value1','value2']

  • for text data , use {"value1","value2"} or array [value1,value2]

Query

Update

Dimensionless

Unnest

Multi Dimensional Array

Array vs JSONB

Advantages to Array

  • It's pretty easy to setup

  • Requires less storage than jsonb

  • It has multi dimensional support

  • Indexing through GIN, greatly speeds up query

  • The PostgreSQL planner is likely to make better decisions with PostgreSQL array, as it collects statistics on its content, but not with JSONB.

Disadvantages to Array

  • Its main advantages is that you are limited to one data type

  • Have to follow strict order of the array data input.

Advantages to JSONB

  • Provides additional operators for querying

  • Support for indexing

Disadvantages to JSONB

  • Has to parse the json data to binary format

  • slow in writing, but faster in reading

  • Doesn't maintain order

Ranges

image

Inclusion Operators

Length and Dimensions

Positions

Search, Replace, Remove

IN, NOT IN, ANY

STRING TO Array

Last updated

Was this helpful?