w3resource

Mastering PostgreSQL Arrays: Functions, Operations, and Examples


Understanding PostgreSQL Arrays

PostgreSQL provides robust support for arrays, enabling you to store and manipulate multi-valued data in a single column efficiently. Arrays are particularly useful for handling list-like data, simplifying queries and reducing the need for additional tables.

1. Defining an Array in PostgreSQL

a. Creating a Table with Array Column

Code:

CREATE TABLE employees (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    skills TEXT[]
);

b. Inserting Data into an Array Column

Code:

INSERT INTO employees (name, skills) VALUES ('Alice', ARRAY['Python', 'SQL', 'Java']);

c. Querying Data with Arrays

Code:

SELECT name, skills FROM employees WHERE 'SQL' = ANY(skills);

2. Array Functions and Operations

Function/Operator Description Example
ARRAY[] Declares an array. ARRAY[1, 2, 3]
' ' (Concatenation)
array_length() Returns the size of an array. array_length(ARRAY[10, 20, 30], 1)
unnest() Expands array into rows. SELECT unnest(ARRAY['a', 'b', 'c'])
array_append() Appends a value to the end of an array. array_append(ARRAY[1, 2], 3)
array_remove() Removes a specific value from the array. array_remove(ARRAY[1, 2, 3], 2)

3. Array Operations Examples

a. Updating an Array

Code:

UPDATE employees
SET skills = array_append(skills, 'Docker')
WHERE name = 'Alice';

b. Removing an Element

Code:

UPDATE employees
SET skills = array_remove(skills, 'Java')
WHERE name = 'Alice';

c. Combining Arrays

Code:

SELECT ARRAY['PostgreSQL', 'MySQL'] || ARRAY['MongoDB', 'Redis'];

4. Using Arrays in WHERE Clause

a. Check if Value Exists in an Array

Code:

SELECT * FROM employees WHERE 'Python' = ANY(skills);

b. Matching Multiple Values

Code:

SELECT * FROM employees WHERE skills @> ARRAY['Python', 'SQL'];

5. Best Practices with PostgreSQL Arrays

Normalization: Avoid arrays for complex relationships; consider a separate table.

Indexing: Use GIN indexes for faster array operations.

Validation: Validate data before inserting into arrays to maintain consistency.

Additional Notes

Arrays can be of any PostgreSQL data type, including user-defined types. Use them judiciously to simplify queries and optimize storage.

All PostgreSQL Questions, Answers, and Code Snippets Collection.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/PostgreSQL/snippets/postgresql-array.php