w3resource

Using the COALESCE Function in PostgreSQL to Handle NULLs


PostgreSQL COALESCE Function: Handling Null Values

In PostgreSQL, the COALESCE function is used to handle NULL values by returning the first non-NULL value from a list of arguments. It’s especially useful for ensuring that queries return usable data, even when some values are missing or undefined. COALESCE is commonly used in SQL queries to provide default values, replace NULL values, or handle optional fields gracefully.

Syntax of COALESCE in PostgreSQL

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

Where -

  • value1, value2, ..., valueN: List of expressions or column names evaluated in order. COALESCE returns the first non-NULL value from this list.
  • If all values are NULL, COALESCE itself returns NULL.

Example 1: Handling NULLs with a Default Value

Suppose you have a table employees with columns first_name, middle_name, and last_name. You want to retrieve a full name, but middle_name may be NULL.

Code:

-- Select full name with middle name if available
SELECT first_name || ' ' || COALESCE(middle_name, '') || ' ' || last_name AS full_name
FROM employees;

Explanation:

  • The COALESCE(middle_name, '') part returns middle_name if it has a value; otherwise, it returns an empty string ('').
  • This avoids NULL values in the concatenation, ensuring full_name is complete.

Example 2: Setting a Default Value for NULL Column Data

Suppose you have a table orders with columns order_id, order_date, and shipping_date. If shipping_date is NULL, you want to display “Pending” instead.

Code:

-- Select orders with a readable shipping status
SELECT order_id, order_date, COALESCE(shipping_date::text, 'Pending') AS shipping_status
FROM orders;

Explanation:

  • The COALESCE(shipping_date::text, 'Pending') returns the shipping_date as text if available; otherwise, it displays “Pending.”
  • This is useful for clearly indicating records with no shipping date yet.

Example 3: Using COALESCE in Aggregations

COALESCE is also helpful in calculations. Suppose a table sales has columns region, revenue, and cost. You want to calculate profit, assuming missing cost values as zero.

Code:

-- Calculate profit considering NULL cost as 0
SELECT region, revenue - COALESCE(cost, 0) AS profit
FROM sales;

Explanation:

  • COALESCE(cost, 0) substitutes a NULL cost value with 0, ensuring profit calculations aren’t skewed by NULL values.

Explanation and Use Cases:

  • Replacing NULLs: COALESCE allows for meaningful data output when some columns have missing values.
  • Default Values: Great for fields with optional data; provides fallback values without altering database structure.
  • Simplified Data Handling: In complex queries with calculations or concatenations, COALESCE helps avoid unexpected NULL results, improving data consistency.
  • Data Aggregation: Ensures that calculations in aggregations or analyses remain accurate, regardless of missing values.

All PostgreSQL Questions, Answers, and Code Snippets Collection.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/PostgreSQL/snippets/postgresql-coalesce.php