patternsqlModerate
array_length if array is empty behaviour
Viewed 0 times
array_lengthbehaviouremptyarray
Problem
Please explain to me this behavior.
This SQL finds elements where ids (type is
This SQL finds no rows:
But this SQL can find non-empty arrays
Initialization:
Why
This SQL finds elements where ids (type is
array::bigint) is empty.SELECT * FROM rises WHERE ids = '{}'
-- finds, e.g., 9 rowsThis SQL finds no rows:
SELECT * FROM rises WHERE array_length(ids, 1) = 0
--finds always 0 rowsBut this SQL can find non-empty arrays
SELECT * FROM rises WHERE array_length(ids, 1) > 0
--finds, e.g., 15 rowsInitialization:
CREATE TABLE rises(
id bigserial,
d1 bigint DEFAULT 0,
ids bigint[] DEFAULT '{}',
PRIMARY KEY (id));Why
array_length can find non-empty arrays but it doesn't work for empty arrays?Solution
It looks like PostgreSQL returns
You get:
Looks weird, but that's just the way it is. The workaround is to use
returns 0.
Tried this on PostgreSQL 9.4.
NULL for empty arrays. Try:SELECT
array_length(ARRAY[]::bigint[], 1),
array_length(ARRAY[]::bigint[], 1) IS NULL,
array_lower(ARRAY[]::bigint[], 1),
array_upper(ARRAY[]::bigint[], 1)You get:
null|true|null|nullLooks weird, but that's just the way it is. The workaround is to use
COALESCE:SELECT
COALESCE(array_length(ARRAY[]::bigint[], 1), 0)returns 0.
Tried this on PostgreSQL 9.4.
Code Snippets
SELECT
array_length(ARRAY[]::bigint[], 1),
array_length(ARRAY[]::bigint[], 1) IS NULL,
array_lower(ARRAY[]::bigint[], 1),
array_upper(ARRAY[]::bigint[], 1)SELECT
COALESCE(array_length(ARRAY[]::bigint[], 1), 0)Context
StackExchange Database Administrators Q#138577, answer score: 12
Revisions (0)
No revisions yet.