How to Use COALESCE in PostgreSQL
Last updated July 25, 2026 · By the SaturnSQL team
COALESCE(a, b, ...) returns the first non-NULL argument, making it the standard way to supply defaults for NULL values. NULLIF(a, b) does the inverse: it returns NULL when the two arguments are equal.
SELECT id,
COALESCE(nickname, first_name, 'Unknown') AS display_name,
COALESCE(discount, 0) AS discount
FROM customers;NULLIF: avoid division by zero
SELECT campaign,
SUM(revenue) / NULLIF(SUM(clicks), 0) AS revenue_per_click
FROM events
GROUP BY campaign;All arguments must be of compatible types; COALESCE(amount, 'none') fails because numeric and text do not mix. Combining them, COALESCE(NULLIF(name, ''), 'Unknown') treats empty strings like NULLs.
Run this in SaturnSQL
SaturnSQL is a browser-based SQL editor for teams: shared query library, schema-aware autocomplete, and scheduled exports to Google Sheets and Slack.
Try it free