Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: CROSS JOIN UNNEST and include data from rows with NULLs in CROSS JOIN UNNEST column

I'm looking for assistance in the below SQL query where column policy_array has NULL values in some rows, but arrays of policy data in others. I would like to be able to include data from rows even when policy_array is NULL in the output.

When I execute the below query it executes a CROSS JOIN UNNEST as expected but also drops all data from columns with NULLs in the column policy_array as expected as well. I can imagine a work around by having an intermediate table where NULLs in policy_array are changed to something else, but I really would prefer not to do that.

 SELECT 
    policy,
    account_id,
    rejects,
    overturns,
    appeals,
    submits
FROM relevant_table
CROSS JOIN UNNEST(policy_array) AS p (policy)
WHERE
    ...
like image 705
Chris Saindon Avatar asked Oct 21 '25 04:10

Chris Saindon


1 Answers

There are two options either LEFT JOIN with on true:

FROM relevant_table
LEFT JOIN UNNEST(policy_array) AS p (policy) ON true

Or a little bit more hackish which uses the fact that unnest supports multiple arrays - add array with one element (also note succinct syntax for cross join unnest):

FROM relevant_table, 
    UNNEST(policy_array, array[1]) AS p (policy, ignored)
like image 161
Guru Stron Avatar answered Oct 22 '25 18:10

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!