cem
cem

Reputation: 39

Postgres Group by ignore nulls

What I want to do should really be basic but for some reason I can't figure it out. Consider the following:

ID, COL1, COL2
1   'A'   NULL
1   NULL  'B'

I want to group on ID and 'squeeze out' the gaps and get:

ID, COL1, COL2
1   'A'   'B'

I'm probably having a black out as this sounds a very sqly problem/solution. This on a very large data set with many rows and columns so efficiency would be important

Upvotes: 3

Views: 3946

Answers (1)

S-Man
S-Man

Reputation: 23666

demo: db<>fiddle

You could simply use an aggregate function which "removes" NULL values. MAX doesn't chose NULL if there's another value for example:

SELECT 
    id, 
    MAX(col1) as col1, 
    MAX(col2) as col2
FROM my_table
GROUP BY id

Upvotes: 3

Related Questions