Set 1 for NOT NULL value in MySQL


To set NOT NULL, use IS NOT NULL and find the value. The syntax is as follows −

select if('' is not NULL,1,0) as anyAliasName;

Here is the working query −

mysql> select if('' is not NULL,1,0);

This will produce the following output −

+------------------------+
| if('' is not NULL,1,0) |
+------------------------+
|                      1 |
+------------------------+
1 row in set (0.00 sec)

To understand the above syntax, let us create a table −

mysql> create table DemoTable1915
   (
   Name varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1915 values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1915 values('');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1915 values('David');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1915 values(NULL);
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1915;

This will produce the following output −

+-------+
| Name  |
+-------+
| Chris |
|       |
| David |
| NULL  |
+-------+
4 rows in set (0.00 sec)

Here is the query to implement IF() and set 1 for NOT NULL −

mysql> select if(Name IS NOT NULL,1,0) as Result from DemoTable1915;

This will produce the following output −

+--------+
| Result |
+--------+
|      1 |
|      1 |
|      1 |
|      0 |
+--------+
4 rows in set (0.00 sec)

Updated on: 30-Dec-2019

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements