How to Compare Arrays in PostgreSQL

In PostgreSQL, arrays are versatile data structures that can store multiple values of the same type. However, comparing arrays can sometimes be tricky, especially when you need to compare them for equality, order, or other conditions. In this tutorial, we’ll dive into various methods of comparing arrays in PostgreSQL.

Basic Array Comparison

To compare arrays for equality, you can use the standard equality operator (=) in PostgreSQL. This will check if two arrays have the same values in the same order.

SELECT ARRAY[1, 2, 3] = ARRAY[1, 2, 3];

The above query will return true because both arrays are identical.

Array Length Comparison

If you only care about the length of the arrays, you can use the array_length function to compare their sizes.

SELECT array_length(ARRAY[1, 2, 3], 1) = array_length(ARRAY[4, 5], 1);

This query will return false because the lengths of the arrays are different.

Comparing Arrays Using Array Functions

PostgreSQL provides several functions to help with array comparisons:

  • array_length: Compares the number of elements in an array.
  • array_positions: Finds positions of elements in the array and can be used for advanced comparisons.

Example:

SELECT array_positions(ARRAY[1, 2, 3, 4], 2);

This will return the position of 2 in the array, which is {2}.

Comparing Arrays with Set Operations

To compare arrays as sets (ignoring order), you can convert them to SET type and then compare:

SELECT ARRAY[1, 2, 3] @> ARRAY[1, 3];

The above query checks whether the array on the left contains all the elements from the array on the right. It will return true because ARRAY[1, 2, 3] contains ARRAY[1, 3].

Array Comparison in Joins

Array comparison can also be useful in joins. Here’s how you can join two tables where one column contains arrays:

SELECT * FROM table1 t1
WHERE ARRAY[1, 2, 3] = t1.array_column;

This query will return rows where the array in array_column is exactly equal to ARRAY[1, 2, 3].

Conclusion

Comparing arrays in PostgreSQL can be simple or advanced depending on your use case. Whether you're checking for equality, comparing lengths, or using set-based operations, PostgreSQL provides robust support for working with arrays.