- 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
Return true or false in a MySQL select if another field contains a string?
To return TRUE or FALSE if another field contains a string, use IF(). Let us first create a table
mysql> create table DemoTable ( FirstName varchar(100), LastName varchar(100) ); Query OK, 0 rows affected (1.28 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Chris','Brown'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('David','Miller'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('Adam','Smith'); Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+----------+ | FirstName | LastName | +-----------+----------+ | Chris | Brown | | David | Miller | | Adam | Smith | +-----------+----------+ 3 rows in set (0.00 sec)
Following is the query to return true or false in a MySQL select if another field contains a string. Here, we are checking for string “Miller” −
Mysql> select if(LastName=’Miller’,’Yes','No') AS LastName,FirstName from DemoTable;
This will produce the following output −
+----------+-----------+ | LastName | FirstName | +----------+-----------+ | No | Chris | | Yes | David | | No | Adam | +----------+-----------+ 3 rows in set (0.00 sec)
Advertisements
To Continue Learning Please Login
Login with Google