Compare for NULL value and display value 1 for these values in a new MySQL column?

MySQLMySQLi Database

For this, use IF() along with IS NULL property. Let us first create a table −

mysql> create table DemoTable
(
   Name varchar(100),
   CountryName varchar(100)
);
Query OK, 0 rows affected (0.70 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Chris','US');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Mike',NULL);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.38 sec)
mysql> insert into DemoTable values('Bob','AUS');
Query OK, 1 row affected (0.45 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+-------------+
| Name  | CountryName |
+-------+-------------+
| Chris | US          |
| Mike  | NULL        |
| David | NULL        |
| Bob   | AUS         |
+-------+-------------+
4 rows in set (0.00 sec)

Following is the query to compare for NULL value and display value 1 for these values in a new MySQL column −

mysql> select Name,CountryName,If (CountryName IS NULL,1,0) AS CountDemo from DemoTable;

This will produce the following output −

+-------+-------------+-----------+
| Name  | CountryName | CountDemo |
+-------+-------------+-----------+
| Chris | US          |         0 |
| Mike  | NULL        |         1 |
| David | NULL        |         1 |
| Bob   |  AUS        |         0 |
+-------+-------------+-----------+
4 rows in set (0.00 sec)
raja
Published on 27-Sep-2019 06:27:27
Advertisements