COALESCE Instead of Verbose CASE in SQL: Picking the First Non-Null Price CleanlyBrief · digest for November 28
Brief≈ 1 min

COALESCE Instead of Verbose CASE in SQL: Picking the First Non-Null Price Cleanly

A product table often holds three prices: SpecialOfferPrice, DiscountedPrice, and ListPrice. Some fields are NULL, and the storefront needs the first non-empty amount by priority. With CASE, you have to type each column name twice.

COALESCE collapses that check into one call: it evaluates left to right and returns the first non-NULL value.

-- Multi-line CASE: column names are repeated
SELECT
  ProductID,
  ProductName,
  CASE
    WHEN SpecialOfferPrice IS NOT NULL THEN SpecialOfferPrice
    WHEN DiscountedPrice IS NOT NULL THEN DiscountedPrice
    ELSE ListPrice
  END AS SellingPrice
FROM Products;

-- Compact COALESCE: priority is obvious at a glance
SELECT
  ProductID,
  ProductName,
  COALESCE(
    SpecialOfferPrice,
    DiscountedPrice,
    ListPrice
  ) AS SellingPrice
FROM Products;

Beyond shorter syntax, COALESCE short-circuits: once it finds a non-null value, it skips evaluating expressions to the right. It is also standard SQL and works across PostgreSQL, MySQL, SQL Server, Oracle, and SQLite—unlike dialect-specific NVL or IFNULL.

Watch one catch: it only filters out NULL. Zero or an empty string counts as a valid value (filter those with COALESCE(NULLIF(SpecialOfferPrice, 0), ...)), and all arguments must be compatible with a common data type.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 2