Set conditions for columns with values 0 or 1 in MySQL


To set conditions, use CASE WHEN statement in MySQL. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Value1 int,
   -> Value2 int,
   -> Value3 int,
   -> Value4 int
   -> );
Query OK, 0 rows affected (0.98 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(1,0,1,1);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(1,0,1,0);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(1,1,1,1);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(0,0,0,0);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+--------+--------+--------+--------+
| Value1 | Value2 | Value3 | Value4 |
+--------+--------+--------+--------+
|     1 |       0 |      1 |      1 |
|     1 |       0 |      1 |      0 |
|     1 |       1 |      1 |      1 |
|     0 |       0 |      0 |      0 |
+--------+--------+--------+--------+
4 rows in set (0.00 sec)

Here is the query to set conditions for columns with values 0 or 1 in MySQL−

mysql> select case when Value1+Value2+Value3+Value4 < 2 then 'NotGood' else 'Good' end as Status from DemoTable;

This will produce the following output −

+---------+
| Status  |
+---------+
| Good    |
| Good    |
| Good    |
| NotGood |
+---------+
4 rows in set (0.00 sec)

Updated on: 26-Feb-2020

502 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements