POSTGRESQL

How to Find Elements In an Array: PostgreSQL Guide

intro

Discover all the possible ways to find elements in a PostgreSQL array or check if it contains one or more elements!

Tools used in the tutorial
Tool Description Link
Dbvisualizer DBVISUALIZER
TOP RATED DATABASE MANAGEMENT TOOL AND SQL CLIENT

As you might already know, PostgreSQL supports arrays. This special data type allows you to store multiple values in a single column as an array. When working with arrays, one of the most common operations is searching for elements within them. Let's explore PostgreSQL find in array approaches!

What Is a PostgreSQL Array?

In PostgreSQL, an array is a data type to store multiple values in a single column. An array can store data of various data types, including integers, text, and more. For more information, refer to our guide on the PostgreSQL data types.

The syntax to add an array column in Postgres is as follows (note the [] addition):

Copy
        
1 ALTER TABLE your_table_name 2 ADD COLUMN tags text[];

This adds a tags column that can store an array of strings.

How to Find One or More Elements in a PostgreSQL Array

Time to discover the most effective PostgreSQL find in array approaches!

The following queries will be executed using DbVisualizer, a top-rated database client with full PostgreSQL support. Some of its features will also come in handy to explore the table to run the queries on.

The following examples will refer to the books table below:

The Data view in DbVisualizer
The Data view in DbVisualizer

As you can see from the DbVisualizer’s Data view, the table contains several book records. In particular, the column of interest is the string array named genres. Here is the SQL DDL definition of the bookstable, as retrieved via DbVisualizer in the DDL view:

The DDL view in DbVisualizer
The DDL view in DbVisualizer

Notice how the genres column is of type TEXT[].

Now we will explore techniques that you can use to get elements from an array in PostgreSQL.

Note: The techniques shown below work with PostgreSQL arrays of any data type.

By Index

The easiest way to get elements from an array in PostgreSQL is by accessing them using their index. For example:

Copy
        
1 SELECT id, title, genres[1] FROM books;

In this query, the genres[1] expression extracts the first element of the genres array from each row:

Note that the genres column contains only a single element per row
Note that the genres column contains only a single element per row

Contains Operator

@>—also known as the PostgreSQL array “contains” operator—allows you to verify if an array contains one or more elements.

For example, suppose you want to retrieve all books where the genres column contains the string “Adventure.” In other words, you want to get all adventure-related books. You can achieve that with the @> operator as follows:

Copy
        
1 SELECT * FROM books 2 WHERE genres @> ARRAY['Adventure'];

Or, equivalently:

Copy
        
1 SELECT * FROM books 2 WHERE genres @> '{"Adventure"}';

Execute one of these queries, and the result will be all books that belong to the "Adventure" genre:

All selected books are adventure books
All selected books are adventure books

All selected books are adventure books

In detail, @> returns true if the array contains the specified value(s) and false otherwise.

You can also use @> to check if an array contains multiple values. For example, to find books that belong to both "Adventure" and "Suspense" genres, use the following query:

Copy
        
1 SELECT * FROM books 2 WHERE genres @> ARRAY['Adventure', 'Suspense'];

Or, equivalently:

Copy
        
1 SELECT * FROM books 2 WHERE genres @> '{"Adventure", "Suspense"}';

The above queries will return all books that have both "Adventure" and "Suspense" as genres:

Now, all selected books are adventure and suspense books
Now, all selected books are adventure and suspense books

“Is Contained By” Operator

To check if an array contains one or more values from another array, you can utilize the <@ operator, known as the "is contained by" PostgreSQL array operator.

For example, suppose you want to get all books with genres that include both "Adventure" and "Suspense." You can achieve that using the <@ operator as follows:

Copy
        
1 SELECT * FROM books 2 WHERE ARRAY['Adventure', 'Suspense'] <@ genres;

Or, equivalently:

Copy
        
1 SELECT * FROM books 2 WHERE '{"Adventure", "Suspense"}' <@ genres;

This query produces the same result as the @> query seen earlier. The main difference is the order of the operands in the WHERE condition.

Overlap Operator

The PostgreSQL && array operator, also known as the "overlap" operator, helps you make sure if two arrays share any common elements. This operator is particularly useful when you want to find rows where an array column contains one or more elements from a given set.

Now, suppose you want to find all books that have either "Horror" or "Crime" as one of the genres. To reach that goal, you can use the && operator as below:

Copy
        
1 SELECT * FROM books 2 WHERE genres && ARRAY['Horror', 'Crime'];

Or, equivalently:

Copy
        
1 SELECT * FROM books 2 WHERE genres && '{"Horror", "Crime"}';

Execute one of the above queries, and the result will be as follows:

All selected books are either horror or thriller books
All selected books are either horror or thriller books

ANY/SOME Function

ANY—or equivalently SOME—is a PostgreSQL function to verify if any element in an array meets a specific condition.

For example, you can use ANY to retrieve all books where the genres array contains the genre “Adventure” like so:

Copy
        
1 SELECT * FROM books 2 WHERE 'Thriller' = ANY(genres);

The result will be:

All selected books are or are also thriller books
All selected books are or are also thriller books

If at least one element in the array matches the specified condition, the row is returned.

array_position Function

The array_position function returns the index of a specific element within an array, if present. Otherwise, it returns NULL.

If you want to find rows that contain the genre "Romance," execute the following query:

Copy
        
1 SELECT * 2 FROM books 3 WHERE array_position(genres, 'Romance') IS NOT NULL;

array_position function searches for "Romance" within the genres column of the books table. If the returned index is not NULL (i.e., genres contains the specified value), the row is selected.

The result will be:

Note how array_positions works well with IS NOT NULL
Note how array_positions works well with IS NOT NULL

unnest Function

The unnest function expands an array into a set of rows, enabling you to apply standard SQL search conditions on the resulting set. You can also use this result to filter records in the main query, as in this example:

Copy
        
1 SELECT * 2 FROM books 3 WHERE 'Thriller' IN (SELECT unnest(genres));

The above query searches for all books that contain the "Thriller" genre in the genres array.

Other Approaches

PostgreSQL provides native array operators and functions for searching within arrays, but you can also follow other approaches.

For example, the array_to_string function converts an array into a string. Then, you can leverage string functions like SQL LIKE, ILIKE, or even regular expressions to find elements within that array.

Now, suppose you want to get all books that have "Suspense" as a genre. Do that with the array_to_string function combined with LIKE:

Copy
        
1 SELECT * 2 FROM books 3 WHERE array_to_string(genres, ',') LIKE '%Suspense%';

array_to_string(genres, ',') converts the genres array into a single string, with each element separated by a comma. Then, LIKE '%Suspense%' searches the resulting string for the specified string. If "Suspense" is found anywhere in the string, the row is returned, as you can see below:

Note the use of array_to_string
Note the use of array_to_string

The problem with this approach is that it would also select books with genres like "Suspense-Thriller." That is because the genre string contains the word "Suspense," as specified in the LIKE condition. Thus, use array_to_string cautiously in PostgreSQL find in array scenarios. Also, keep in mind that converting all arrays to strings takes time and may make your queries slow.

Conclusion

In this guide, you learned how to access elements, search for elements, and check if specific elements are present in an array in PostgreSQL. You are now a master of PostgreSQL find in array approaches!

As demonstrated, working with arrays becomes easier with a powerful and visual database client, and this is where DbVisualizer comes in!

DbVisualizer is a robust database client that supports multiple DBMS technologies and is equipped with advanced features such as query optimization, SQL formatting, and ERD-like schema generation. Try DbVisualizer for free today!

FAQ

Is it possible to search for data in an array in Postgres?

Yes, you can use built-in operators and functions for PostgreSQL find in array implementations. For instance, you can take advantage of array operators like @> (contains) and <@ (is contained by), along with functions such as ANY(), unnest(), and array_position().

How to find an element in a JSON array in PostgreSQL?

There are a few approaches you can follow to find an element in a JSON array in PostgreSQL. First, you can use jsonb_array_elements` to expand a JSONB array into a set of rows and search in them with a subquery:

Copy
        
1 SELECT * 2 FROM books 3 WHERE EXISTS ( 4 SELECT 1 5 FROM jsonb_array_elements(genres) AS genre 6 WHERE genre = '"Adventure"' 7 );

Find out more about SQL subqueries.

Second, you can use the @> with a JSON array on the right:

Copy
        
1 SELECT * 2 FROM books 3 WHERE genres @> '["Adventure"]';

Third, you can utilize a JSONPATH expression as below:

Copy
        
1 SELECT * 2 FROM books 3 WHERE genres @? '$[*] == "Adventure"';

For more information, read our guide on PostgreSQL JSONPATH.

Why should I use an SQL client?

Using an SQL client, such as DbVisualizer, is beneficial because it enables you to visualize your data, making your development tasks easier. A good SQL client offers a variety of tools that simplify data management and analysis, regardless of the database management system you're working with. These features enhance productivity, streamline workflows, and help you gain insights from your data more effectively.

Dbvis download link img
About the author
Antonello Zanini

Antonello is a software engineer, and often refers to himself as a technology bishop. His mission is to spread knowledge through writing.

The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

What Is a PostgreSQL Primary Key?

author Leslie S. Gyamfi tags POSTGRESQL 8 min 2024-12-18
title

SQL CHECK Constraint: Definitive Guide With Examples

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-12-16
title

A Guide To the SQL DECLARE Statement

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SERVER 7 min 2024-12-12
title

SQL Upsert: Inserting a Record If It Does Not Exist

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-12-10
title

How and Why to Add an Index in SQL

author Lukas Vileikis tags MySQL POSTGRESQL Search SQL SQL SERVER 8 min 2024-11-28
title

List of SQL Reserved Words in All Major Databases

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 16 min 2024-11-20
title

SQL Variable: What It Is and How To Use It

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-11-18
title

Postgres DATEDIFF Equivalent Functions: Calculating Date and Time Differences

author Lukas Vileikis tags POSTGRESQL 6 min 2024-11-04
title

CREATE SCHEMA PostgreSQL Statement: What, Why & When to Use

author Lukas Vileikis tags POSTGRESQL 4 min 2024-10-30
title

SQL EXPLAIN: The Definitive Tool to Optimize Queries

author Antonello Zanini tags MySQL POSTGRESQL SQL 12 min 2024-10-29

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.