Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL unnest with empty array

Tags:

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

id | ... | values
-----------------------
1  | ... | {1,2,3}
2  | ... | {}

where id is an integer and values is an integer array. The arrays can be empty.

I need to unnest this list. If I query

select id, ..., unnest(values)
from table

I get three rows for id = 1 (as expected) and no lines for id = 2. Is there a way to get a result like

id  | ... | unnest
-------------------
1   | ... | 1
1   | ... | 2
1   | ... | 3
2   | ... | null

i.e. a query which also contains the lines which have an empty array?

like image 839
rams Avatar asked Mar 02 '13 13:03

rams


2 Answers

select id, 
       case 
         when int_values is null or array_length(int_values,1) is null then null
         else unnest(int_values)
       end as value
from the_table;

(note that I renamed the column values to int_values as values is a reserved word and should not be used as a column name).

SQLFiddle: http://sqlfiddle.com/#!1/a0bb4/1


Postgres 10 does not allow to use unnest() like that any more.

You need to use a lateral join:

select id, t.i
from the_table
   cross join lateral unnest(coalesce(nullif(int_values,'{}'),array[null::int])) as t(i);

Online example: http://rextester.com/ALNX23313


It can be simplified even further when using a left join instead of the cross join:

select id, t.i
from the_table
 left join lateral unnest(int_values) as t(i) on true;

Online example: http://rextester.com/VBO52351

like image 183
a_horse_with_no_name Avatar answered Sep 21 '22 14:09

a_horse_with_no_name


This works on Postgres 10 also:

SELECT id, UNNEST(CASE WHEN "values" <> '{}' THEN "values" ELSE '{null}' END)
like image 25
Eduardo Avatar answered Sep 22 '22 14:09

Eduardo