sql / intermediate
Snippet
Handling Nulls with COALESCE
COALESCE takes a list of arguments and returns the first non-null value. It is essential for providing fallback values when dealing with optional columns in a database.
snippet.sql
1
2
3
SELECT employee_name,COALESCE(personal_phone, work_phone, 'No Phone') AS contact_numberFROM employees;
Breakdown
1
COALESCE(personal_phone, work_phone, 'No Phone')
Evaluates fields in order; if personal is null, checks work; if both are null, uses the string.
2
AS contact_number
Renames the calculated output column for better readability.