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 →Example
Handling NULLs in Retail Calculations
SELECT order_id, channel, revenue - COALESCE(discount, 0) AS net_revenue
FROM orders| order_id | channel | net_revenue |
|---|---|---|
| O2001 | Online | 105.0 |
| O2002 | In-Store | 85.5 |
| O2003 | Online | 170.0 |
| O2004 | Mobile | |
| O2005 | Mobile | 60.0 |
Step by step
- Run the query without COALESCE so you can see what the unfiltered values look like.
SELECT order_id, channel, revenue - discount FROM orders; - COALESCE returns the first non-NULL value from the arguments.
SELECT order_id, channel, revenue - COALESCE(discount, 0) FROM orders; - 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
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 customers2. 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 products3. 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 orders4. 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 inventory5. 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 reviewsLearn 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 →