IFNULL() tests its first argument and returns it if it's not NULL, or returns its second argument otherwise
mysql>
mysql> CREATE TABLE mytable
-> (
-> name CHAR(20),
-> id CHAR(20)
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO mytable (name,id) VALUES ('Tom','198-48');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO mytable (name,id) VALUES ('Jack',NULL);
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO mytable (name,id) VALUES ('Mary',NULL);
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO mytable (name,id) VALUES ('Jane','475-83');
Query OK, 1 row affected (0.00 sec)
mysql>
mysql> SELECT * FROM mytable;
+------+--------+
| name | id |
+------+--------+
| Tom | 198-48 |
| Jack | NULL |
| Mary | NULL |
| Jane | 475-83 |
+------+--------+
4 rows in set (0.00 sec)
mysql>
mysql> SELECT name, IFNULL(id,'Unknown') AS 'id' FROM mytable;
+------+---------+
| name | id |
+------+---------+
| Tom | 198-48 |
| Jack | Unknown |
| Mary | Unknown |
| Jane | 475-83 |
+------+---------+
4 rows in set (0.00 sec)
mysql>
mysql> drop table mytable;
Query OK, 0 rows affected (0.00 sec)
Related examples in the same category