MySQL IFNULL() and COALESCE()

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.

IFNULL()

SELECT id, name, IFNULL(class, 'not known') AS class, mark
FROM student3;

Output:

idnameifnull(class,'not known')mark
1John DeoFour
2Max Ruinnot known85
3ArnoldThree
4Krish Starnot known
5John MikeFour
6Alex Johnnot known55
7My John Rob55
8AsruidFive85
9Tes QrySix78

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;

COALESCE()

Sample customer data:

idfirst_namemiddle_namelast_name
1King
2Queen
3Jack
4
5ArnoldKSt
6Ravi
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:

idname
1King
2Queen
3Jack
4
5Arnold
6Ravi

Aggregate functions and NULL

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;

Download student3 SQL dump

Customer sample table

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');



Subscribe to our YouTube Channel here



plus2net.com




SQL Video Tutorials










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer