Arrays
In PostgreSQL, defining an array is a simple process. An array is specified by adding square brackets to a valid data type. This could range from an array of integers, text, boolean values, etc.
In this case, my_array
is an array of integers. This column can now store multiple integer values.
Insert Records
To initialize an array with values, one can utilize the ARRAY constructor. Below is an illustration demonstrating the process of inserting data into the table that has just been created:
View Records
To access individual elements in an array, you use square brackets. Remember, arrays in PostgreSQL are 1-indexed, meaning the first element is at position 1. Here's an example:
Functions
array_append(array, element)
: This function appends an element to the end of an array
array_prepend(element, array)
: This function adds an element to the beginning of an array.
array_length(array, dimension)
: This function returns the length of the requested array dimension.
unnest(array)
: This function "flattens" an array into a set of rows.
Querying Array
The ANY
keyword allows you to check if any element in an array matches a condition.
This statement returns all rows where my_array
contains the value 3
.
The ALL
keyword is used to check if all elements in an array satisfy a condition.
This statement returns all rows where all values in my_array
are less than 3
.
Last updated