MySQL Wildcards

MySQL Wildcards

MySQL Aliases

MySQL Aliases

MySQL Data Types

MySQL Data Types

MySQL Interview Questions

MySQL Interview Questions and Answers


MySQL EXISTS Operator

In MySQL, EXISTS operator allows you to check existence of any record in a subquery. The EXISTS operator return true if the subquery returns at least one row. The EXISTS operator can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

Note: MySQL statements that use the EXISTS Condition are not efficient since the sub-query is RE-RUN for EVERY row in the outer query's table.

MySQL EXISTS OPERATOR Syntax

To check existence of any record in a subquery, use the following syntax:

Syntax

SELECT col1, col2,....
FROM tablename
WHERE EXISTS (SELECT col1 FROM tablename WHERE condition); 

Parameters:

tablename: The table name from which you want to perform EXISTS operator.

subquery: Usually a SELECT statement starts with SELECT * or column name. MySQL ignores the SELECT list from subquery.

MySQL EXISTS OPERATOR example with SELECT statement

The following MySQL, EXISTS operator is uses the MySQL EXISTS operator:

Example

SELECT A.accountName FROM tblbankdemataccountcharges A 
WHERE EXISTS (SELECT B.banks FROM tblbankheadquartersandaddress B WHERE A.bankId = B.pk) LIMIT 5;

Note:

In the above example, the EXISTS operator will return all records from the "tblbankdemataccountcharges" table where there is at least one record in the tblbankheadquartersandaddress table with the matching "bankId".

You can use MySQL Command Line Client to use EXISTS operator in subquery. It will look like this: