0

I have the following table in Postgresql. The first 4 records are the base data and the others were generated with the ROLLUP function.

I want to add a column "grp_1" that will display the first non-null value of the columns grp1_l1, grp2_l2 and grp2_l3

enter image description here

I can get to the desired result by nesting 3 "case" functions using the SQL below, but my real table has 4 groups with each 8 to 10 columns (so a lot of nested "case" function).

sql:

SELECT grp1_l1, grp1_l2, grp1_l3, case when grp1_l1 is not null then grp1_l1 else case when grp1_l2 is not null then grp1_l2 else case when grp1_l3 is not null then grp1_l3 else null end end end as grp1, value
FROM public.query_test;

Is there a better and more scalable to handle this requirement ? Any suggestions are welcome. The id will not always have 3 digits, that is just the case in my example here

1
  • coalesce(c1, c2, c3, ...) Commented Jul 16, 2020 at 12:46

1 Answer 1

3

Use coalesce() it's defined as "returns the first of its arguments that is not null" - which is exactly what you want.

coalesce(grp1_l1, grp1_l2, grp1_l3)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, exactly what I was looking forward, did not realize there was a function specifically for that use case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.