How to check whether column value is NULL or having DEFAULT value in MySQL?


You can use the concept of IFNULL() for this. Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(100) DEFAULT 'Larry',
   Age int DEFAULT NULL
);
Query OK, 0 rows affected (0.73 sec)

Insert records in the table using insert command −

mysql> insert into DemoTable(Name,Age) values('John',23);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(Age) values(24);
Query OK, 1 row affected (0.13 sec)

Following is the query to display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
| 1  | John  | 23   |
| 2  | Larry | NULL |
| 3  | David | NULL |
| 4  | Larry | 24   |
+----+-------+------+
4 rows in set (0.00 sec)

Following is the query to check whether column value is NULL or having DEFAULT value in MySQL.

mysql> select *from DemoTable WHERE IFNULL(Name, DEFAULT(Name)) <> DEFAULT(Name);

This will produce the following output −

+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
| 1  | John  | 23   |
| 3  | David | NULL |
+----+-------+------+
2 rows in set (0.00 sec)

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

384 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements