How do you use COALESCE in PostgreSQL?
Answer
COALESCE(val1, val2, ..., valN) returns the first non-NULL value in its argument list. It is the SQL standard equivalent of a null-safe "or default" operation. Example: SELECT COALESCE(nickname, first_name, 'Anonymous') FROM users; — uses nickname if not null, else first_name, else the literal 'Anonymous'. Useful for: providing default values, handling optional fields, avoiding NULL in output. COALESCE(SUM(col), 0) returns 0 instead of NULL when no rows match. It evaluates arguments left to right and stops at the first non-NULL. It's equivalent to CASE WHEN val1 IS NOT NULL THEN val1 WHEN val2 IS NOT NULL THEN val2 ... END but much more concise.
Previous
What is a subquery in PostgreSQL?
Next
What are some common string functions in PostgreSQL?