Given a table defined as such:
CREATE TABLE test_values(name TEXT, values INTEGER[]);
...and the following values:
| name | values |
+-------+---------+
| hello | {1,2,3} |
| world | {4,5,6} |
I'm trying to find a query which will return:
| name | value |
+-------+-------+
| hello | 1 |
| hello | 2 |
| hello | 3 |
| world | 4 |
| world | 5 |
| world | 6 |
I've reviewed the upstream documentation on accessing arrays, and tried to think about what a solution using the unnest()
function would look like, but have been coming up empty.
An ideal solution would be easy to use even in cases where there were a significant number of columns other than the array being expanded and no primary key. Handling a case with more than one array is not important.
You can put the set-returning function
unnest()
into theSELECT
list like Raphaël suggests. But in Postgres 9.3 or later use aLATERAL
join for this instead. It is the cleaner, preferable, standard-compliant way to put set-returning functions into theFROM
list, not into theSELECT
list:One subtle difference: this drops rows with empty / NULL
values
from the result sinceunnest()
returns no row, while the same is converted to a NULL value in theFROM
list and returned anyway. The 100 % equivalent query is:Well, you give the data, the doc, so... let's mix it ;)
see SqlFiddle