PostgreSQL: Insert/Query/Update/Delete array data

Updated: January 6, 2024 By: Guest Contributor Post a comment

Overview

This tutorial covers essential operations on array data types in PostgreSQL, including inserting, querying, updating, and deleting. Master database manipulations by dealing with arrays using a variety of code examples.

Introduction to PostgreSQL Arrays

PostgreSQL offers robust support for array data types, which can simplify data representation of concepts such as lists, vectors, or sets directly within a single database column. Arrays can be one-dimensional, or can be multidimensional, storing arrays of arrays. Understanding how to manipulate these data types efficiently can power up your database operations.

Before we start altering array data, let’s set up the environment first:

CREATE TABLE my_table (
    id SERIAL PRIMARY KEY,
    data TEXT[],
    numbers INT[]
);

This table will be used as a reference for all our examples. It contains two columns for array data, one for textual data and another for integer values.

Inserting Array Data

To insert data into our newly created table, you’ll typically use the following PostgreSQL INSERT command:

INSERT INTO my_table (data, numbers)
VALUES ('{item1,item2,item3}', '{1,2,3}');

Array literals in PostgreSQL are entered using curly braces {} and separated by commas.

Querying Array Data

Once you have data in the table, you can start querying the array:

SELECT * FROM my_table WHERE 2 = ANY(numbers);

The ANY keyword allows you to check if the array contains the integer 2. The result includes all rows where ‘2’ is an element in the ‘numbers’ array. You can also use array positions in the WHERE clause:

SELECT data[1] FROM my_table;

This query fetches the first element from each array in the ‘data’ column.

Updating Array Data

To update elements in an array, utilize the array index. To change the second element of the ‘numbers’ array to 5 for all records:

UPDATE my_table SET numbers[2] = 5;

It’s also possible to append an element to an array:

UPDATE my_table SET data = array_append(data, 'new_item');

And to remove an element at a specific index:

UPDATE my_table
SET data = data[1:array_lower(data, 1)-1] || data[array_upper(data, 1)+1:array_length(data, 1)];

Remember that PostgreSQL arrays are 1-indexed, not 0-indexed like in many programming languages.

Deleting Array Data

If you want to delete a row based on an array condition:

DELETE FROM my_table WHERE 'itemToDelete' = ANY(data);

You can also empty a specific array with:

UPDATE my_table SET data = '{}';

Advanced Array Manipulations

In addition to basic manipulations, PostgreSQL offers advanced features for array operations:

Using Array Expressions

Finding rows with arrays that include all elements of another array:

SELECT * FROM my_table WHERE data @> '{item1,item2}';

The @> operator stands for ‘contains’. To check for overlap between two arrays:

SELECT * FROM my_table WHERE numbers && '{2,4}';

Slicing Arrays

You might want to select portions of arrays:

SELECT data[1:2] FROM my_table;

This will return the first two items of the ‘data’ column’s arrays.

Using Arrays in Functions

Some functions can transform or give insights into the arrays. For instance, to unnest an array into a set of rows:

SELECT unnest(numbers) FROM my_table;

Getting array dimensions:

SELECT array_dims(numbers) FROM my_table;

Combining arrays:

SELECT data || '{additional,item}' FROM my_table;

Handling Multidimensional Arrays

A multidimensional array requires consistent subarray lengths. To manipulate or query them, refer to each dimension by its index:

UPDATE my_table SET numbers[1:2][1:3] = '{{4,5,6},{7,8,9}}' WHERE id = 1;

Above updates a portion of a two-dimensional array.

Remember, multidimensional arrays can grow quickly and become complex, so use them prudently.

You can see the detailed guide about multidimensional arrays in Postgres in this article: Using multi-dimensional arrays in PostgreSQL.

Conclusion

In this tutorial, we’ve explored PostgreSQL’s capacity to manage array data types for varied and complex data storage needs. Whether you’re working with one-dimensional lists or multidimensional arrays, PostgreSQL provides the SQL tools necessary to make data manipulation efficient and effective. From basic operations like inserting and querying to advanced updates, the versatility of array data will ensure your databases can scale with complexity while remaining performant.