IFNULL() and COALESCE() let a query substitute a value when data is NULL. IFNULL(expr1, expr2) accepts two expressions; COALESCE() can test a list and returns the first non-NULL expression.
SELECT id, name, IFNULL(class, 'not known') AS class, mark
FROM student3;
Output:
| id | name | ifnull(class,'not known') | mark |
|---|---|---|---|
| 1 | John Deo | Four | |
| 2 | Max Ruin | not known | 85 |
| 3 | Arnold | Three | |
| 4 | Krish Star | not known | |
| 5 | John Mike | Four | |
| 6 | Alex John | not known | 55 |
| 7 | My John Rob | 5 | 5 |
| 8 | Asruid | Five | 85 |
| 9 | Tes Qry | Six | 78 |
The replacement affects the query result only; it does not update the stored value.
SELECT id, name, class, IFNULL(mark, 1) * 2 AS doubled_mark
FROM student3;
SELECT id, name, class, 100 / IFNULL(mark, 1) AS score_ratio, mark
FROM student3;
Sample customer data:
| id | first_name | middle_name | last_name |
|---|---|---|---|
| 1 | King | ||
| 2 | Queen | ||
| 3 | Jack | ||
| 4 | |||
| 5 | Arnold | K | St |
| 6 | Ravi |
SELECT id, name, class, 100 / COALESCE(mark, 1) AS score_ratio, mark
FROM student3;
SELECT COALESCE(first_name, last_name) AS full_name
FROM customer;
When several columns can contain a value, COALESCE() returns the first non-NULL item in the list.
SELECT id, COALESCE(first_name, middle_name, last_name) AS name
FROM customer;
Output:
| id | name |
|---|---|
| 1 | King |
| 2 | Queen |
| 3 | Jack |
| 4 | |
| 5 | Arnold |
| 6 | Ravi |
Aggregate functions such as MAX(), MIN() and COUNT(column) ignore NULL values. COUNT(*) counts rows regardless of whether individual columns contain NULL.
SELECT MAX(mark) FROM student3;
SELECT MIN(mark) FROM student3;
SELECT COUNT(*) FROM student3;
SELECT COUNT(mark) FROM student3;
CREATE TABLE customer (
id INT NOT NULL,
first_name VARCHAR(10) DEFAULT NULL,
middle_name VARCHAR(10) DEFAULT NULL,
last_name VARCHAR(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO customer (id, first_name, middle_name, last_name) VALUES
(1, NULL, 'King', NULL),
(2, NULL, NULL, 'Queen'),
(3, 'Jack', NULL, NULL),
(4, NULL, NULL, NULL),
(5, 'Arnold', 'K', 'St'),
(6, NULL, NULL, 'Ravi');
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.