
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check Multiple Columns for a Single Value in MySQL
You can check multiple columns for one value with the help of IN operator. The syntax is as follows −
select *from yourTableName where value IN(yourColumnName1, yourColumnName2,......N);
To understand the above concept, let us create a table with some columns. The query to create a table is as follows −
mysql> create table OneValueFromAllColumns −> ( −> StudentId int, −> StudentFirstname varchar(200), −> StudentLastname varchar(200), −> StudentAge int −> ); Query OK, 0 rows affected (1.41 sec)
Insert some records in the table with the help of select statement. The query is as follows −
mysql> insert into OneValueFromAllColumns values(1,'John','Smith',23); Query OK, 1 row affected (0.14 sec) mysql> insert into OneValueFromAllColumns values(2,'Carol','Taylor',22); Query OK, 1 row affected (0.18 sec) mysql> insert into OneValueFromAllColumns values(3,'Maria','Garcia',19); Query OK, 1 row affected (0.16 sec) mysql> insert into OneValueFromAllColumns values(4,'Bob','Wilson',21); Query OK, 1 row affected (0.22 sec)
Display all records which we have inserted above. The query to display all records from the table is as follows −
mysql> select *from OneValueFromAllColumns;
The following is the output −
+-----------+------------------+-----------------+------------+ | StudentId | StudentFirstname | StudentLastname | StudentAge | +-----------+------------------+-----------------+------------+ | 1 | John | Smith | 23 | | 2 | Carol | Taylor | 22 | | 3 | Maria | Garcia | 19 | | 4 | Bob | Wilson | 21 | +-----------+------------------+-----------------+------------+ 4 rows in set (0.00 sec)
Here is the query to check multiple columns for single value. We are checking for the value “Taylor’ in multiple columns i.e. StudentId, StudentFirstname, StudentLastname and StudentAge.
The query is as follows −
mysql> select *from OneValueFromAllColumns where 'Taylor' IN(StudentId,StudentFirstname,StudentLastname,StudentAge);
The following is the output that displays the record with the value “Taylor” −
+-----------+------------------+-----------------+------------+ | StudentId | StudentFirstname | StudentLastname | StudentAge | +-----------+------------------+-----------------+------------+ | 2 | Carol | Taylor | 22 | +-----------+------------------+-----------------+------------+ 1 row in set, 4 warnings (0.03 sec)
Advertisements