Languages
[Edit]
EN

MySQL - IFNULL() function example

0 points
Created by:
Keisha-Acosta
380

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:

MySQL - IFNULL() function result
MySQL - IFNULL() function result

Practical example

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

MySQL - example data used with IFNULL() function
MySQL - example data used with IFNULL() function

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:

MySQL - IFNULL() function result
MySQL - IFNULL() function 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');
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join