Counting Array Length in PostgreSQL
When it comes to counting the elements in these arrays, PostgreSQL provides two useful functions: array_length
and cardinality
.
Using array_length
The array_length
function is specifically designed to find the length of a specified dimension in an array. Here's how you can use it:
SELECT array_length(array_column, 1) FROM your_table;
This function takes two arguments: the array itself and the dimension of the array you want to measure. Since PostgreSQL arrays are 1-based, the second argument is typically 1 for one-dimensional arrays.
Using cardinality
Introduced in PostgreSQL 9.5, the cardinality
function is a more straightforward approach to counting array elements, as it does not require specifying the dimension:
SELECT cardinality(array_column) FROM your_table;
This function simply returns the total number of elements in the array, regardless of its dimensions, making it more versatile for multi-dimensional arrays.
array_length
vs cardinality
Both array_length
and cardinality
are useful for counting array elements, but they have different strengths. The array_length
function is helpful when dealing with multi-dimensional arrays and you need to count elements in a specific dimension. On the other hand, cardinality
offers a simpler and more direct approach, especially useful when you just need the total count of elements across all dimensions of an array. If you're using PostgreSQL 9.5 or later, cardinality
might be the preferred choice due to its simplicity and versatility. However, for earlier versions or specific dimensional counts, array_length
is necessary.
Turn your SQL into Beautiful Dashboards
Create amazing KPI dashboards directly from your SQL database with Dashase
- Create charts, tables, and widgets
- Collaboration - Shared Dashboards
- AI assisted query generation - GPT-4
- Supports PostgreSQL, MySQL, SQL Server, and more
PostgreSQL Snippets
- Counting Array Length in PostgreSQL
- Concatenating Strings in PostgreSQL
- Joining strings with separators in PostgreSQL - CONCAT_WS()
- How to Count Null and Non-Null Values in PostgreSQL
- How to create a table in PostgreSQL
- How to delete rows in PostgreSQL
- How to perform full text search in PostgreSQL
- Handling NULL values with the COALESCE function
- How to insert rows into a table in PostgreSQL
- List databases in PostgreSQL
- Split string in PostgreSQL using regexp_split_to_array
- Split string in PostgreSQL using split_part
- Using substring() to get parts of a string in PostgreSQL
- How to update rows in PostgreSQL