EN
MySQL - IFNULL() function example
0 points
In this article, we would like to show you IFNULL()
function example in MySQL.
Quick solution:
xxxxxxxxxx
1
SELECT IFNULL(expression, value_if_null);
The IFNULL()
function returns the specified value if the expression is NULL
, otherwise it returns the expression.
In this example, we will pass NULL
value as the expression, so it will return the specified text value.
Query:
xxxxxxxxxx
1
SELECT IFNULL(NULL, 'dirask is awesome!');
Result:

To show IFNULL()
function practical example, we will use the following users
table:

Note:
At the end of this article you can find database preparation SQL queries.
In this example, we will select all the rows from users
table and return the information if the user's email wasn't specified using IFNULL()
function.
Query:
xxxxxxxxxx
1
SELECT
2
`id`, `name`, `email`,
3
IFNULL(`email`, 'not specified') AS 'email_info'
4
FROM `users`;
Result:

create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE `users` (
2
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
3
`name` VARCHAR(50) NOT NULL,
4
`email` VARCHAR(50),
5
PRIMARY KEY (`id`)
6
);
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO `users`
2
( `name`, `email`)
3
VALUES
4
('John', 'john@email.com'),
5
('Chris', NULL),
6
('Kate', NULL),
7
('Ailisa', 'ailisa@email.com'),
8
('Gwendolyn', NULL),
9
('Simon', 'simon@email.com'),
10
('Taylor', NULL),
11
('Andrew', 'andrew@emal.com');