PostgreSQL – CARDINALITY Function

The cardinality function in PostgreSQL is used to determine the number of elements in an array. It returns an integer value representing the size or length of the array. The cardinality function is particularly useful when you need to find out how many elements are in an array so that you can perform various calculations or checks based on the array’s size.

Below is the syntax for the cardinality function:

cardinality(array_expression)

array_expression is the array for which you want to determine the number of elements.

Below is an example of how to use the cardinality function:

Consider an array of integers as shown below:

SELECT cardinality(ARRAY[1, 2, 3, 4, 5])

The result of this query would be: 5

It returns 5 because there are five elements in the array.

You can use the cardinality function in various situations, such as:

  • Checking if an array is empty or not (cardinality(array_expression) = 0).
  • Using it in conditional statements to perform actions based on the array’s size.
  • Combining it with other functions to create complex queries that depend on the size of arrays.

Similar Posts