Skip to content
Advertisement

Replace NULL values per partition

I want to fill NULL values in device column for each session_id with an associated non-NULL value. How can I achieve that?

Here is the sample data:

Desired output:

Advertisement

Answer

The window function first_value() with the right ordering is probably cheapest:

db<>fiddle here

ORDER BY device IS NULL, step sorts NULL values last, so the earliest step with a notnull value is picked. See:

If notnull devices per session_id are always the same, you can simplify to just ORDER BY device IS NULL. And you don’t need COALESCE.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement