HiveBrain v1.2.0
Get Started
← Back to all entries
gotchaMajor

Difference between GROUP BY B,A and GROUP BY COALESCE(B,A)

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
groupcoalescedifferencebetweenand

Problem

I have been getting myself very confused.

Could somebody kindly explain under what circumstances I would want to use a GROUP BY COALESCE?

My guess is that I would use it if I wanted to conditionally group a set of data by column B (if B was not null) and by column A otherwise. Does that sound right?

Solution

With GROUP BY b,a the tuples (null, 1), (1,1), (2,1) and (17,1) would end up in four different groups.

With GROUP BY coalesce(b,a) the tuples (null,1), (1,1), (2,1) and (17,1) would end up in the same group.

If you want the "conditional" grouping, then yes, the version with coalesce is probably what you want.

Context

StackExchange Database Administrators Q#9143, answer score: 37

Revisions (0)

No revisions yet.