BBampaa

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 →
About 5–10 minutes · no sign-up needed

Example

Fill in empty cells

SELECT order_id, customer_id, COALESCE(discount, 0) AS discount
FROM orders

Result:

order_idcustomer_iddiscount
O2001C10115.0
O2002C1020
O2003C1035.5
O2004C1040
O2005C10520.0

Step by step

  1. Where discount is empty, show 0 instead.
    SELECT order_id, customer_id, COALESCE(discount, 0) AS discount FROM orders
  2. Cells that already have a value don't change.
    SELECT order_id, customer_id, COALESCE(discount, 0) AS discount FROM orders
  3. Works with text: put the fill-in value in quotes.
    SELECT order_id, customer_id, COALESCE(discount, 0) AS discount FROM orders

Practice

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

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 customers
2. 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 products
3. 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 orders
4. 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 inventory
5. 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 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