Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions ebook/en/content/018-essential-mysql-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,3 +189,43 @@ SELECT TIME_TO_SEC('09:00') - TIME_TO_SEC('09:02')
```
-120

## NULL Handling Functions

These functions are essential for managing and substituting `NULL` (missing) values, ensuring your queries return clean and predictable data.

### IFNULL()

Returns the first expression if it is not `NULL`. Otherwise, it returns the second expression. This is a quick way to provide a default value for a single column.

> Assume the `employees` table has a `bonus` column that may contain NULL values.
```sql
SELECT IFNULL(bonus, 0) FROM employees;
```
If bonus is NULL, the output is 0. Otherwise, it shows the bonus amount.

### COALESCE()

Returns the first non-NULL value from a list of expressions. It's useful when you have multiple potential sources for a value.

Suppose you have a `players` table with columns for different types of nicknames:

| id | formal_nickname | fan_alias |
|----|----------------|-----------|
| 1 | NULL | "Ace" |
| 2 | "The Rocket" | NULL |
| 3 | NULL | NULL |

The following query returns the first available nickname for each player, or 'No Nickname' if all are NULL:
```sql
SELECT COALESCE(formal_nickname, fan_alias, 'No Nickname') FROM players;
```
Returns the first available nickname or 'No Nickname' if all are NULL.

```sql
SELECT COALESCE(NULL, NULL, NULL)

```sql
SELECT COALESCE('First Value', 'Second Value', 'Third Value')
```
First Value