Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplified UNNEST with STRUCT de-structuring #123

Open
pilosoposerio opened this issue Nov 17, 2024 · 3 comments
Open

Simplified UNNEST with STRUCT de-structuring #123

pilosoposerio opened this issue Nov 17, 2024 · 3 comments

Comments

@pilosoposerio
Copy link

The following CTE block:

unnested_changed_records AS (
SELECT player_name,
(records::scd_type).scoring_class,
(records::scd_type).is_active,
(records::scd_type).start_season,
(records::scd_type).end_season
FROM changed_records
),

can be simplified to (using CROSS JOIN to the UNNESTed array):

unnested_changed_records AS ( 
  
     SELECT c.player_name, 
           r.*
            FROM changed_records c, UNNEST(c.records) r
     ), 

provided that you remove the UNNEST call in changed_records.records (i.e., just leave records as an ARRAY):

UNNEST(ARRAY[
ROW(
ls.scoring_class,
ls.is_active,
ls.start_season,
ls.end_season
)::scd_type,
ROW(
ts.scoring_class,
ts.is_active,
ts.current_season,
ts.current_season
)::scd_type
]) as records

This is especially helpful when your scd_type has a lot more fields and you need to de-structure them all.

@BUBLET
Copy link

BUBLET commented Nov 17, 2024

Looks good to merge, but I’d recommend adding a check for when the records array is empty—just to avoid any issues with UNNEST.

@redpandaxl
Copy link

is this easier to read than using the deconstructor?

(unnest(ARRAY[
               (ls.scoring_class, ls.is_active, ls.start_season, ls.end_season)::scd_type,
               (ts.scoring_class, ts.is_active, ts.current_season, ts.current_season)::scd_type
           ])).*

@BUBLET
Copy link

BUBLET commented Nov 19, 2024

CROSS JOIN and UNNEST is actually easier, especially if there're many fields
There's no need to explicity specify each field during deconstruction and thus no risk of manual errors

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants