Lessons › SQL › Chapter 4: Shaping data
SQL lesson
COALESCE()
COALESCE(discount, 0) shows 0 wherever discount is empty, and keeps the value everywhere else. It only changes your result, not the table. It works with text too: COALESCE(email, 'No email').
Try this lesson free →Example
Fill in empty cells
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
- Where discount is empty, show 0 instead.
SELECT order_id, customer_id, COALESCE(discount, 0) AS discount FROM orders - Cells that already have a value don't change.
SELECT order_id, customer_id, COALESCE(discount, 0) AS discount FROM orders - Works with text: put the fill-in value in quotes.
SELECT order_id, customer_id, COALESCE(discount, 0) AS discount FROM orders
Practice
1. Using customers, show email, and next to it email again with 'No email' where it's missing. Name the second column email_filled.
SELECT email, COALESCE(email, 'No email') AS email_filled FROM customers2. Using products, show brand, and next to it brand again with 'Unbranded' where it's missing. Name the second column brand_filled.
SELECT brand, COALESCE(brand, 'Unbranded') AS brand_filled FROM products3. Using orders, show customer_id, and next to it customer_id again with 'Guest' where it's missing (guest checkouts). Name the second column customer_id_filled.
SELECT customer_id, COALESCE(customer_id, 'Guest') AS customer_id_filled FROM orders4. Using inventory, show stock_count, and next to it stock_count again with 0 where it's missing. Name the second column stock_count_filled.
SELECT stock_count, COALESCE(stock_count, 0) AS stock_count_filled FROM inventory5. Using reviews, show review_id, and next to it comment with 'No comment' where it's missing. Name it comment_filled.
SELECT review_id, COALESCE(comment, 'No comment') AS comment_filled 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 →