Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
postgresql display two sublists in one result

Assuming the very simple schema

table main

main_id, ...
1      , ...
2      , ...

table sub1

main_id, sub1_data
1      , a
1      , b
2      , g

table sub2

main_id, sub2_data
1      , 1
2      , 1
2      , 2

As output I would like

main_id, sub1_data, sub2_data
1      , a        , 1
1      , b        , <null>
2      , g        , 1
2      , <null>   , 2

Using a union I can get close but then each list get's it's own rows

SELECT main_id, sub1_data, NULL
FROM sub1
UNION 
SELECT main_id, NULL, sub2_data
FROM sub2

result

main_id, sub1_data, sub2_data
1      , a        , <null>
1      , b        , <null>
1      , <null>   , 1
2      , g        , <null>
2      , <null>   , 1
2      , <null>   , 2

So is there a way to get them two share rows and just use as many rows as the longest list?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

One thing which can give you this "interleaved" output is the unnest() function with multiple parameters (or its equivalent: the ROWS FROM(...) construct):

Table functions may also be combined using the ROWS FROM syntax, with the results returned in parallel columns; the number of result rows in this case is that of the largest function result, with smaller results padded with null values to match.
...
The special table function UNNEST may be called with any number of array parameters, and it returns a corresponding number of columns, as if UNNEST had been called on each parameter separately and combined using the ROWS FROM construct.

select     main_id, sub1_data, sub2_data
from       (select main_id, array_agg(sub1_data) sub1_arr from sub1 group by main_id) s1
full join  (select main_id, array_agg(sub2_data) sub2_arr from sub2 group by main_id) s2 using (main_id)
cross join unnest(sub1_arr, sub2_arr) u(sub1_data, sub2_data)

http://rextester.com/QSWESJ84203

Note: this is a "relatively" new feature: it was introduced in 9.4

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!