1

Let's say I have the following field and values:

ArrayField
[1,2,3]
[3,4,5]
[null,2,3,4]
null
[]
[null]

Would postgres save all these values as-is. Or would any of these values be invalid or converted to something else -- for example having null as a field value (is that converted to [])?

3
  • 2
    jsonb or integer[]? Commented Jan 15, 2020 at 20:58
  • []........... Commented Jan 15, 2020 at 21:01
  • 2
    null and an empty array [] are two different things Commented Jan 15, 2020 at 21:02

2 Answers 2

3

In Postgres, all of your expressions are valid excepted for the last one: '{null,}', which would raise error:

malformed array literal: "{null,}"

It is also worth noting that there is a difference between null (and undefined value) and {} (an empty array). Say you want to write to a column has a not null constraint, null would fail while {} would be allowed.

Demo on DB Fiddle:

-- create the table
create table t (array_field int[])

-- insert values
insert into t values
    ('{1,2,3}'),
    ('{3,4,5}'),
    ('{null,2,3,4}'),
    (null),
    ('{}')
;
-- 5 rows affected

-- won't work
insert into t values ('{null,}');
-- ERROR:  malformed array literal: "{null,}"
-- LINE 1: insert into t values ('{null,}')
--                               ^
-- DETAIL:  Unexpected "}" character.

-- check the results
select array_field, array_length(array_field, 1) from t
array_field  | array_length
:----------- | -----------:
{1,2,3}      |            3
{3,4,5}      |            3
{NULL,2,3,4} |            4
null         |         null
{}           |         null
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for this, I updated the syntax for this. One question -- what would be an example where [] would be different than null in a practical usage (not just in terms of storage value)?
@David542: welcome. Well, you can see in my answer the example of an insert query against a non-nullable column.
1

PostgreSQL will not silently modify your arrays. If you stored [NULL], it won't become []. Your last example ([NULL,]) is syntactically incorrect.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.