diff --git a/datafusion/functions-nested/src/length.rs b/datafusion/functions-nested/src/length.rs index 9579c3c9cd658..b1550af7cd686 100644 --- a/datafusion/functions-nested/src/length.rs +++ b/datafusion/functions-nested/src/length.rs @@ -188,7 +188,9 @@ fn compute_array_length( loop { if current_dimension == dimension { - return Ok(Some(value.len() as u64)); + // PostgreSQL: array_length(anyarray, dimension) returns NULL when that + // dimension is empty (`array_length('{}'::int[], 1)`), not zero. + return Ok((!value.is_empty()).then(|| value.len() as u64)); } match value.data_type() { diff --git a/datafusion/sqllogictest/test_files/array/array_length.slt b/datafusion/sqllogictest/test_files/array/array_length.slt index 1bb5382339854..ba784b29404fc 100644 --- a/datafusion/sqllogictest/test_files/array/array_length.slt +++ b/datafusion/sqllogictest/test_files/array/array_length.slt @@ -65,11 +65,16 @@ select array_length(arrow_cast(array_repeat(array_repeat(array_repeat(3, 5), 2), ---- 3 2 -# array_length scalar function #5 +# array_length scalar function #5 empty array dimension (PostgreSQL-compatible) query III select array_length(make_array()), array_length(make_array(), 1), array_length(make_array(), 2) ---- -0 0 NULL +NULL NULL NULL + +query I +SELECT array_length(ARRAY[]::INT[], 1) +---- +NULL # array_length scalar function #6 nested array query III