PostgreSQL Tutorial

Data Types

Querying & Filtering Data

Managing Tables

Modifying Data

Conditionals

Control Flow

Transactions & Constraints

Working with JOINS & Schemas

Roles & Permissions

Working with Sets

Subquery & CTEs

User-defined Functions

Important In-Built Functions

PostgreSQL PL/pgSQL

Variables & Constants

Stored Procedures

Working with Triggers

Working with Views & Indexes

Errors & Exception Handling

PostgreSQL - Array Data Type

PostgreSQL supports the ARRAY data type, which allows you to store one-dimensional arrays (vectors) or multi-dimensional arrays (matrices) of a specific data type. Arrays can be useful for various purposes, such as storing and processing sets of values within individual table columns.

Basic Syntax and Usage:

  1. Defining an Array Column:

    When defining a column of an array type, you specify the base data type followed by square brackets [].

    CREATE TABLE table_name (
        column_name data_type[]
    );
    

    For example, to create a table students with a column grades that stores an array of integers:

    CREATE TABLE students (
        id serial PRIMARY KEY,
        name text,
        grades int[]
    );
    
  2. Inserting Data:

    Use curly braces {} to denote array literals.

    INSERT INTO students (name, grades) VALUES ('John', '{90, 85, 82}');
    
  3. Querying Data:

    To retrieve a specific element from an array, use the array index. Remember, array indices in PostgreSQL start at 1, not 0.

    SELECT grades[1] FROM students WHERE name = 'John';  -- This retrieves the first grade of John.
    

    To get the entire array:

    SELECT grades FROM students WHERE name = 'John';
    
  4. Array Length:

    Use the array_length function to determine the length of an array.

    SELECT array_length(grades, 1) FROM students WHERE name = 'John';
    
  5. Array Functions and Operators:

    PostgreSQL provides various functions and operators for working with arrays, such as array_append, array_prepend, array_cat (concatenation), and others.

    -- Append a value to the grades array
    UPDATE students SET grades = array_append(grades, 88) WHERE name = 'John';
    

Multi-dimensional Arrays:

You can also define multi-dimensional arrays. For instance, a two-dimensional array can be considered a table, and a three-dimensional array can be seen as a cube of values.

-- Define a two-dimensional array
CREATE TABLE matrix (
    id serial PRIMARY KEY,
    data int[][]
);

-- Insert data into the two-dimensional array
INSERT INTO matrix (data) VALUES ('{{1,2,3},{4,5,6},{7,8,9}}');

Points to Remember:

  • While arrays can be powerful, it's essential to ensure you don't violate the principles of database normalization without a good reason. In many scenarios, using related tables can be a better choice than arrays.

  • If you need to query based on the contents of arrays frequently or if the array content is crucial for the application's logic, you might want to evaluate whether a different database design would be more appropriate.

  • Always be cautious of potential performance implications when working with large arrays or executing operations that need to scan through each array element.

  1. Creating arrays in PostgreSQL:

    • Description: How to create arrays in PostgreSQL.
    • Code Example:
      SELECT ARRAY[1, 2, 3] AS integer_array,
             ARRAY['apple', 'banana', 'orange'] AS text_array;
      
  2. Inserting and updating array values in PostgreSQL:

    • Description: Adding or modifying array elements in PostgreSQL.
    • Code Examples:
      -- Inserting values into an array column
      UPDATE your_table
      SET integer_array_column = integer_array_column || 4
      WHERE id = 1;
      
      -- Updating specific array element
      UPDATE your_table
      SET text_array_column[2] = 'grape'
      WHERE id = 1;
      
  3. Querying arrays in PostgreSQL:

    • Description: Retrieving data based on array conditions.
    • Code Example:
      SELECT *
      FROM your_table
      WHERE 3 = ANY(integer_array_column);
      
  4. Working with multidimensional arrays in PostgreSQL:

    • Description: Handling arrays with multiple dimensions.
    • Code Example:
      SELECT ARRAY[[1, 2], [3, 4]] AS two_dimensional_array;
      
  5. Modifying array elements in PostgreSQL:

    • Description: Changing specific elements within an array.
    • Code Example:
      UPDATE your_table
      SET integer_array_column[1] = 99
      WHERE id = 1;
      
  6. Using array functions in PostgreSQL:

    • Description: Utilizing built-in array functions.
    • Code Example:
      -- Finding the length of an array
      SELECT array_length(integer_array_column, 1) AS array_length
      FROM your_table
      WHERE id = 1;
      
  7. Array aggregation and grouping in PostgreSQL:

    • Description: Aggregating values into arrays and grouping by arrays.
    • Code Example:
      -- Aggregating values into an array
      SELECT group_id, ARRAY_AGG(value) AS value_array
      FROM your_table
      GROUP BY group_id;