Postgres - How to check for an empty array
In PostgreSQL, use your_array = '{}'
or cardinality(your_array) = 0
to determine if your_array
is empty. Both methods will return true
for an empty array.
Here is an example using comparison:
And here is one using cardinality
function:
These checks give you quick and easy ways to detect an empty array without the need for complex functions or subqueries.
Checking Array Bounds Using PostgreSQL Functions
For an alternative method, consider the array_upper
and array_lower
functions. These can identify an empty array by evaluating its bounds.
Why does this work? The bounds of an empty array in PostgreSQL are NULL
. Hence, array_upper
returns NULL
when there are no elements in the array, much like a party where nobody showed up. 🥳
Potholes on the Road: Common Mistakes to Avoid
Be cautious to not mistake ARRAY[NULL]::array_datatype
or ARRAY(SELECT 1 WHERE FALSE)
as symbols of an empty array. They either represent an array with NULL
or a fancy way to complicate your query, respectively. Just like putting a "Beware of the Dog" sign doesn't mean you have a dog!
Literal Translation: Understanding Array Literals
In PostgreSQL, if we query for '{}'
, it is understood as an empty array. It's important to enclose array literals with proper quotation marks and braces:
This is similar to handing in a blank paper when you're clueless during an exam. It's not wrong; it's just empty!
Version Discrepancies: Cardinality Availability
Consider the PostgreSQL version when using the cardinality
function, as it was introduced only in PostgreSQL 9.4. If you're stuck with an earlier version, you're stuck with array_upper
and array_lower
, or other crafted solutions. Kind of like wanting an iPhone 13 when you still have the iPhone 4!
Ever-Present Presence-checks: Practical Usage of Empty Array Checks in Queries
When you're engaged in the practical world of SQL queries, you might find yourself needing to execute actions based on the emptiness of an array:
Let the Counting Games Begin: Counting Rows with Empty Arrays
I Smell Humans!: Filtering Out Empty Arrays
Empty? You're Out!: Conditional UPDATE/DELETE Operations
Just like in a horror movie, if you're empty, you're toast!
NULL-ifying the Problem: Dealing with NULLs in Arrays
Consider an important nuance when working with arrays that contain NULL values. An array with a NULL is different from an empty array:
This will return false
because an array with a NULL
is not entirely empty. It's like saying a box with only air isn't empty!
Was this article helpful?