- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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)
- Related Articles
- Set multiple values for custom columns in MySQL?
- Using UNIQUE for varchar columns with some conditions in MySQL?
- Display only the default values set for columns in MySQL
- Set conditions while adding column values in MySQL?
- Set DEFAULT values for columns while creating a table in MySQL
- Count values based on conditions and display the result in different columns with MySQL?
- Should I use MySQL enum or tinyint for fields having values 1 and 0?
- SET only two values for all the rows in a MySQL table based on conditions?
- MySQL query with OR & AND conditions
- Set different IDs for records with conditions using a single MySQL query
- Set a custom value for NULL or empty values in MySQL
- How to create conditions in a MySQL table with multiple columns?
- Set all values in a MySQL field to 0?
- Populate null columns in a MySQL table and set values
- MongoDB query to get documents with multiple conditions set in $or?

Advertisements