4

I have table t with an array column z in Postgres 9.5. I want to select id where z is either NULL OR {NULL}.

id |   z
---+--------
 1 | {NULL} 
 2 |  null     

See DBFIDDLE

I tried changing {NULL} to NULL with array_remove():

SELECT id, 
array_remove(z,NULL) as removed
from t;

Returns:

id |    z   | removed 
---+--------+-------
 1 | {NULL} |   {}      
 2 |  null  |  null

However, if I query this:

select id, z from t where removed is null;

I still get id 1. Ideally, I'd like to avoid unnesting and grouping back up.

4
  • 3
    Please provide table definition. demo Commented Jan 5, 2019 at 20:18
  • 1
    The question is misleading, it would be good if you could make it clearer. If I understand the title well, you need nullif(z, '{null}') Commented Jan 5, 2019 at 21:50
  • I edited the question as best I could and added a dbfiddle (demo)[dbfiddle.uk/… Commented Jan 5, 2019 at 22:28
  • It's still not clear, what you are trying to achieve: The table definition in your fiddle has an integer field z. You write "where z is either null OR {NULL}" but z can't be {NULL} given your table definition. Commented Jan 5, 2019 at 23:15

1 Answer 1

10

To replace an array containing a single NULL element ('{NULL}') with NULL, I suggest NULLIF:

SELECT id, NULLIF(z, '{NULL}') AS z
FROM   t;

db<>fiddle here

'{NULL}' is an (untyped) array literal and the same value as resulting from ARRAY[NULL] - which defaults to the data type text[] without explicit input type or casting.

The above works for any array type: int[], date[], ... because the literal is coerced to the type of z implicitly.

An empty array ('{}') or an array with 1 or more NULL elements ('{NULL}', '{NULL, NULL}', ...) are not the same as NULL. array_remove() is not the right tool.

Sign up to request clarification or add additional context in comments.

2 Comments

Correct link for array literal
@Constantine: While my link wasn't wrong, yours is better. I updated accordingly, thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.