- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements