SQL

SQL COALESCE Function: Syntax, Usage, and Examples

The SQL COALESCE function helps you handle missing or null values in queries by returning the first non-null value from a list of expressions. It’s a standard tool for ensuring clean, readable output and preventing issues when working with incomplete data.

How to Use the SQL COALESCE Function

Use the SQL COALESCE function by passing in multiple values or columns as arguments. The function evaluates each one in order and returns the first that isn’t NULL.

COALESCE(value1, value2, ..., valueN)

You can apply this to both static values and columns. It’s a versatile replacement for writing complex CASE or IF logic when checking for NULL values.

You can add COALESCE wherever you'd normally use a column or value: in SELECT, WHERE, JOIN, or even in calculations.

When to Use the SQL COALESCE Function

Provide Default Fallback Values

Use COALESCE to return a default value when a field is missing. For instance, if a user hasn't entered their city, display "Unknown" instead.

Clean Up Reports

In reporting queries, missing values can disrupt calculations or create gaps in visualizations. Use COALESCE to display a placeholder so users always see something meaningful.

Prevent Errors in Arithmetic

NULL values break most math operations. Use the COALESCE function to substitute zeros or safe defaults and keep your totals accurate.

Examples of the SQL COALESCE Function

Basic Example with a Fallback Value

You can assign a backup value if a column is null.

SELECT name, COALESCE(phone, 'No phone number') AS contact
FROM employees;

This replaces any null phone numbers with a human-friendly message.

Multiple Columns for a Single Result

Let’s say you store a user’s contact methods in different columns. Use COALESCE to grab the first one available:

SELECT name, COALESCE(email, phone, 'No contact info') AS primary_contact
FROM users;

This example checks for an email, then phone, and falls back to a default message.

In Calculations

Replace nulls with a value like zero to keep math from breaking.

SELECT order_id, COALESCE(discount, 0) AS discount_applied, price - COALESCE(discount, 0) AS final_price
FROM orders;

Without COALESCE here, subtracting from a NULL discount would return NULL as the final price.

Learn More About the SQL COALESCE Function

How It Differs from ISNULL and NVL

In SQL Server, you also have the IS NULL() function. While similar, IS NULL() only checks two values and doesn’t follow the ANSI SQL standard. The SQL COALESCE function works across databases like PostgreSQL, MySQL, and SQL Server and accepts more than two inputs:

-- SQL Server specific
ISNULL(discount, 0)

-- Portable across databases
COALESCE(discount, 0)

Oracle uses NVL, which functions similarly but with its own syntax. If you're writing for multiple systems, stick with COALESCE.

Use COALESCE in SQL Server

In SQL Server, the COALESCE functions just like in other environments. It works in computed columns, expressions, joins, and even in stored procedures.

SELECT COALESCE(NULL, NULL, 'Fallback value') AS result;

This returns 'Fallback value' since all previous values are null.

You can also use the SQL Server COALESCE function in more dynamic queries, like:

SELECT name, COALESCE(middle_name, '') + ' ' + last_name AS full_name
FROM people;

This constructs a full name and leaves out the middle name when it’s not provided.

Filter Based on Fallback Values

Imagine you want to filter customers who don’t have an email but do have another form of contact. You could write:

SELECT name
FROM customers
WHERE COALESCE(email, phone) IS NOT NULL;

This helps you filter the data even if the field you're checking changes.

Use in GROUP BY and Aggregates

You might need to group results by a fallback value. Use COALESCE to turn NULL into something usable:

SELECT COALESCE(department, 'Unassigned') AS department_name, COUNT(*) AS total
FROM employees
GROUP BY COALESCE(department, 'Unassigned');

Without this, the null group would be hidden or labeled inconsistently.

Combine COALESCE with JOINs

You can smooth over missing data in joins by assigning fallback labels or values directly in your query:

SELECT e.name, COALESCE(d.name, 'No Department') AS dept_name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.id;

This makes sure every employee appears, even if they’re not assigned to a department.

Format Output for Frontend Applications

Frontend apps or dashboards often expect a clean string, number, or label. Use COALESCE to create a fallback when exporting or preparing your data:

SELECT order_id, COALESCE(shipping_address, billing_address) AS delivery_address
FROM orders;

This gives your application a consistent field, no matter how the data was entered.

Handle Date Values

Null dates are tricky, especially in reports. Use COALESCE to fill them with a placeholder date or timestamp:

SELECT user_id, COALESCE(last_login, '1900-01-01') AS last_login_date
FROM users;

You can also use dynamic values like the current date:

SELECT COALESCE(last_login, GETDATE()) AS recent_activity
FROM users;

This treats nulls as if the user just logged in, useful for previewing layouts or generating synthetic test data.

Use with Nested Queries

COALESCE works well inside subqueries. For example, if you need to get the most recent status but want a backup value:

SELECT user_id,
       COALESCE(
           (SELECT TOP 1 status FROM logs WHERE logs.user_id = users.id ORDER BY created_at DESC),
           'Unknown'
       ) AS latest_status
FROM users;

This example pulls a nested query and still uses a fallback when nothing’s found.

Combine With CASE for Granular Logic

You can pair COALESCE with CASE expressions for fine-grained control:

SELECT name,
       CASE
           WHEN COALESCE(email, phone) IS NULL THEN 'Missing contact info'
           ELSE 'Has contact info'
       END AS contact_status
FROM customers;

This type of logic is especially helpful in validation scripts or data quality checks.

The SQL COALESCE function gives you the power to clean, standardize, and simplify your queries—without needing bulky conditional logic. Whether you're smoothing out a report, validating data before processing, or merging columns for output, COALESCE handles nulls gracefully and keeps your SQL clean.

Learn SQL for Free
Start learning now
button icon
To advance beyond this tutorial and learn SQL by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH