Lessons › SQL › Chapter 4: Shaping data
SQL lesson
COALESCE()
COALESCE() scans a list of values and returns the first one that isn't NULL.
Try this lesson free →Example
Replacing Missing Retail Discounts with COALESCE()
SELECT order_id, customer_id, COALESCE(discount, 0) AS discount
FROM orders| order_id | customer_id | discount |
|---|---|---|
| O2001 | C101 | 15.0 |
| O2002 | C102 | 0 |
| O2003 | C103 | 5.5 |
| O2004 | C104 | 0 |
| O2005 | C105 | 20.0 |
Step by step
- Run the query without COALESCE so you can see what the unfiltered values look like.
SELECT order_id, customer_id, discount FROM orders; - COALESCE returns the first non-NULL value from the arguments.
SELECT order_id, customer_id, COALESCE(discount, 0) FROM orders; - AS gives the COALESCE result a friendly column name so the output reads cleanly.
SELECT order_id, customer_id, COALESCE(discount, 0) AS discount FROM orders;
Practice
1. Using customers, write a query that shows signup_date but replaces NULL values with 0.
SELECT COALESCE(signup_date, 0) FROM customers2. Using products, write a query that shows brand but replaces NULL values with 'Unknown'.
SELECT COALESCE(brand, 'Unknown') FROM products3. Using orders, write a query that shows customer_id but replaces NULL values with 'Unknown'.
SELECT COALESCE(customer_id, 'Unknown') FROM orders4. Using inventory, write a query that shows warehouse but replaces NULL values with 'Unknown'.
SELECT COALESCE(warehouse, 'Unknown') FROM inventory5. Using reviews, write a query that shows product_id but replaces NULL values with 'Unknown'.
SELECT COALESCE(product_id, 'Unknown') 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 →