EN
MySQL - IFNULL() function example
0
points
In this article, we would like to show you IFNULL()
function example in MySQL.
Quick solution:
SELECT IFNULL(expression, value_if_null);
Simple example
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:
SELECT IFNULL(NULL, 'dirask is awesome!');
Result:
Practical example
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.
Example
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:
SELECT
`id`, `name`, `email`,
IFNULL(`email`, 'not specified') AS 'email_info'
FROM `users`;
Result:
Database preparation
create_tables.sql
file:
CREATE TABLE `users` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
`email` VARCHAR(50),
PRIMARY KEY (`id`)
);
insert_data.sql
file:
INSERT INTO `users`
( `name`, `email`)
VALUES
('John', 'john@email.com'),
('Chris', NULL),
('Kate', NULL),
('Ailisa', 'ailisa@email.com'),
('Gwendolyn', NULL),
('Simon', 'simon@email.com'),
('Taylor', NULL),
('Andrew', 'andrew@emal.com');