COALESCE, NULLIF & Type Casting
COALESCE – the first non-NULL value
COALESCE(a, b, c, …) returns the first argument that isn't NULL.
- Default for display:
COALESCE(city, 'Unknown') - Fallback chain:
COALESCE(nickname, first_name, email) - Treat a missing number as zero:
COALESCE(sum(amount), 0)(sum of no rows is NULL!)
NULLIF – turn a value into NULL
NULLIF(a, b) returns NULL if a = b, otherwise a.
- Avoid division by zero:
total / NULLIF(count, 0) - Treat empty strings as missing:
NULLIF(trim(note), '') - Combine them:
COALESCE(NULLIF(trim(city), ''), 'Unknown')
Type casting
Convert a value from one type to another:
- PostgreSQL style:
'42'::int,amount::text,'2026-11-24'::date - Standard SQL:
CAST('42' AS INT) - Typed literals:
DATE '2026-11-24',INTERVAL '3 days',NUMERIC '1.5'
Common casts
| From | To | Example |
|---|---|---|
| text | int/numeric | '250'::numeric |
| numeric | int | 7.8::int → 8 (rounds!) |
| text | date | '2026-11-24'::date |
| timestamp | date | created_at::date |
| boolean | text | true::text → 'true' |
| any | text | 123::text |
⚠️ Invalid casts raise an error: 'abc'::int fails. Clean the data first, or (in PostgreSQL 16+) test with pg_input_is_valid('abc', 'integer').
Implicit conversion
PostgreSQL converts some types automatically (e.g. int + numeric → numeric), but it's stricter than MySQL — comparing a number to text often needs an explicit cast. Explicit is better than surprising.
Example
-- COALESCE: defaults for missing data
SELECT name,
COALESCE(city, 'Unknown') AS city,
COALESCE(monthly_budget, 0) AS budget,
COALESCE(monthly_budget::text, 'Not set') AS budget_label
FROM users
WHERE city IS NULL OR monthly_budget IS NULL;
-- Maya Karki | Pokhara | 0 | Not set
-- Hari Shrestha | Unknown | 15000 | 15000.00
-- sum() of no rows is NULL → COALESCE to 0
SELECT u.name, COALESCE(sum(e.amount), 0) AS total_spent
FROM users u
LEFT JOIN expenses e ON e.user_id = u.id
GROUP BY u.id
ORDER BY total_spent;
-- Maya 0, Hari 0, ...
-- NULLIF: avoid division by zero
SELECT 1000 / NULLIF(0, 0) AS safe_division; -- NULL instead of an error
-- NULLIF + COALESCE: blank strings become a default
SELECT COALESCE(NULLIF(trim(' '), ''), 'No note') AS cleaned; -- 'No note'
-- Casting
SELECT '250.75'::numeric + 100 AS text_to_number, -- 350.75
7.8::int AS rounded_int, -- 8
CAST('2026-11-24' AS date) + 1 AS tomorrow, -- 2026-11-25
now()::date AS today,
amount::int AS whole_rupees
FROM expenses WHERE id = 1;
-- Check before casting (PostgreSQL 16+)
SELECT v, pg_input_is_valid(v, 'numeric') AS ok
FROM (VALUES ('1200'), ('1,200'), ('abc')) AS t(v);
-- 1200 → true | 1,200 → false | abc → false