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 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.
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[] );
Inserting Data:
Use curly braces {}
to denote array literals.
INSERT INTO students (name, grades) VALUES ('John', '{90, 85, 82}');
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';
Array Length:
Use the array_length
function to determine the length of an array.
SELECT array_length(grades, 1) FROM students WHERE name = 'John';
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';
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}}');
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.
Creating arrays in PostgreSQL:
SELECT ARRAY[1, 2, 3] AS integer_array, ARRAY['apple', 'banana', 'orange'] AS text_array;
Inserting and updating array values in PostgreSQL:
-- 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;
Querying arrays in PostgreSQL:
SELECT * FROM your_table WHERE 3 = ANY(integer_array_column);
Working with multidimensional arrays in PostgreSQL:
SELECT ARRAY[[1, 2], [3, 4]] AS two_dimensional_array;
Modifying array elements in PostgreSQL:
UPDATE your_table SET integer_array_column[1] = 99 WHERE id = 1;
Using array functions in PostgreSQL:
-- Finding the length of an array SELECT array_length(integer_array_column, 1) AS array_length FROM your_table WHERE id = 1;
Array aggregation and grouping in PostgreSQL:
-- Aggregating values into an array SELECT group_id, ARRAY_AGG(value) AS value_array FROM your_table GROUP BY group_id;