BBampaa

Lessons › SQL › Deep Dive: Text, Date & Number Functions

SQL lesson

Null handling in calculations

Missing values in SQL are contagious - any calculation that touches one automatically produces another missing value instead of a number. Before substituting a zero or any stand-in, it's worth deciding what the missing data actually represents, because the right fallback is a business judgment, not a technical default.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Handling NULLs in Retail Calculations

SELECT order_id, channel, revenue - COALESCE(discount, 0) AS net_revenue
FROM orders

Result:

order_idchannelnet_revenue
O2001Online105.0
O2002In-Store85.5
O2003Online170.0
O2004Mobile
O2005Mobile60.0

Step by step

  1. Run the query without COALESCE so you can see what the unfiltered values look like.
    SELECT order_id, channel, revenue - discount
    FROM orders;
  2. COALESCE returns the first non-NULL value from the arguments.
    SELECT order_id, channel, revenue - COALESCE(discount, 0)
    FROM orders;
  3. AS gives the COALESCE result a friendly column name so the output reads cleanly.
    SELECT order_id, channel, revenue - COALESCE(discount, 0) AS net_revenue
    FROM orders;

Practice

Try each one in your head first, then open the answer.

1. Using customers, write a query that adds full_name and 0 together, treating any NULL values as 0.
SELECT COALESCE(full_name, 0) + COALESCE(0, 0) FROM customers
2. Using products, write a query that adds price and 0 together, treating any NULL values as 0.
SELECT COALESCE(price, 0) + COALESCE(0, 0) FROM products
3. Using orders, write a query that adds revenue and 0 together, treating any NULL values as 0.
SELECT COALESCE(revenue, 0) + COALESCE(0, 0) FROM orders
4. Using inventory, write a query that adds stock_count and 0 together, treating any NULL values as 0.
SELECT COALESCE(stock_count, 0) + COALESCE(0, 0) FROM inventory
5. Using reviews, write a query that adds rating and 0 together, treating any NULL values as 0.
SELECT COALESCE(rating, 0) + COALESCE(0, 0) FROM reviews

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed