Here's a preview from my zine, Become a SELECT Star! If you want to see more comics like this, sign up for my saturday comics newsletter or browse more comics!
get the zine!
read the transcript!
COALESCE is a function that returns the first argument you give it that isn’t NULL
COALESCE(NULL, 1, 2) => 1
COALESCE(NULL, NULL, NULL) => NULL
COALESCE(4, NULL, 2) => 4
2 ways you might want to use COALESCE in practice:
- Set a default value:
In this table, a NULL discount means there’s no discount, so we use COALESCE to set the default to O:
SELECT name,
price - COALESCE(discount, 0) as net_price
FROM products
products:
| name | price | discount |
|---|---|---|
| orange | 200 | NULL |
| apple | 100 | 23 |
| lemon | 150 | NULL |
query output:
| name | net_price |
|---|---|
| orange | 200 |
| apple | 77 |
| lemon | 150 |
- Use data from 2 (or more!) different columns
This query gets the best guess at a customer’s state:
SELECT customer,
COALESCE(mailing_state, billing_state, ip_address_state) AS state
FROM addresses
(Mailing address, most accurate. If not, try billing address. As a last resort, use their IP address)
| customer | mailing_state | billing_state | ip_address_state |
|---|---|---|---|
| 1 | Bihar | Bihar | Bihar |
| 2 | NULL | Kerala | Kerala |
| 3 | NULL | NULL | Punjab |
| 4 | Gujarat | Punjab | Gujarat |
| state |
|---|
| Bihar |
| Kerala |
| Punjab |
| Gujarat |