- 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
How to correctly enclose subquery in MySQL?
You need to close the subquery in a parenthesis. The syntax is as follows −
select if((select count(*) from yourTableName ),'Yes','No') as anyAliasName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table SelectIfDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(10) -> ); Query OK, 0 rows affected (1.03 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into SelectIfDemo(Name) values('John'); Query OK, 1 row affected (0.21 sec) mysql> insert into SelectIfDemo(Name) values('Carol'); Query OK, 1 row affected (0.17 sec) mysql> insert into SelectIfDemo(Name) values('Larry'); Query OK, 1 row affected (0.12 sec) mysql> insert into SelectIfDemo(Name) values('Bob'); Query OK, 1 row affected (0.22 sec) mysql> insert into SelectIfDemo(Name) values('Sam'); Query OK, 1 row affected (0.15 sec)
Now you can display all records from the table using a select statement. The query is as follows −
mysql> select *from SelectIfDemo;
The following is the output −
+----+-------+ | Id | Name | +----+-------+ | 1 | John | | 2 | Carol | | 3 | Larry | | 4 | Bob | | 5 | Sam | +----+-------+ 5 rows in set (0.00 sec)
Here is the correct way to use a subquery inside enclose parenthesis. The query is as follows −
mysql> select if((select count(*) from SelectIfDemo),'Yes','No') as Result;
The following is the output −
+--------+ | Result | +--------+ | Yes | +--------+ 1 row in set (0.00 sec)
Advertisements