Skip to content
Advertisement

Postgresql work with null rows after joins

For example, we have next query:

Is there way to simplify work with replacing null to 0?

Advertisement

Answer

Yes, with COALESCE:

It accepts multiple arguments and works left to right returning the first non null:

Is the equivalent of

And it is SQL standard so should work on all compliant databases


PG also supports ISNULL and IFNULL which work similarly but I don’t usually recommend them over COALESCE because they don’t exist in all databases/don’t necessarily work equivalently and aren’t as flexible because they only accept 2 arguments. For me this isn’t enough to justify saving 2 characters.. (And if you forget about COALESCE, and you end up doing ISNULL(ISNULL(ISNULL(first, second), third), 0) the SQL is more messy)

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