PostgreSQL unnest with empty array

前端 未结 5 1952
刺人心
刺人心 2021-02-12 23:23

I use postgreSQL 9.1. In my database there is a table which looks like

id | ... | values
-----------------------
1  | ... | {1,2,3}
2  | ... | {}
5条回答
  •  星月不相逢
    2021-02-12 23:42

    Upon revisiting this question it struck me that this can be simpler and faster.
    Reverse the logic of the currently accepted solution by @a_horse:

    SELECT id, CASE WHEN values <> '{}' THEN unnest(values) END AS value
    FROM   tbl
    
    • This returns a row with NULL in value for an empty array as well as for a NULL array, because only an array with elements in it produces TRUE in the test values <> '{}'.

    • Works for arrays of any type, since the literal '{}' is automatically coerced to a matching type.

    • Without explicit ELSE branch, CASE returns NULL, which is what we want anyway.

    • Arrays with a NULL elements will return rows regardless.
      However. I found an anomaly there and posted a question concerning that:

      • NULL emements lost when casting result of unnest()

      Turned out to be a bug that was fixed after my report for pg 9.3+.

提交回复
热议问题