SQLite - EXISTS Operator
The SQLite EXISTS Operator is used to test the existence of records from a subquery. It returns true if the subquery returns one or more records, else returns false.
Syntax
The syntax for using EXISTS operator in SQLite is given below:
SELECT column1, column2, column3, ... FROM table_name WHERE EXISTS (SELECT column_name FROM table_name WHERE condition);
Example:
Example:
Consider a database containing tables called Employee and Contact_Info with the following records:
Table 1: Employee table
EmpID | Name | City | Age | Salary |
---|---|---|---|---|
1 | John | London | 25 | 3000 |
2 | Marry | New York | 24 | 2750 |
3 | Jo | Paris | 27 | 2800 |
4 | Kim | Amsterdam | 30 | 3100 |
5 | Ramesh | New Delhi | 28 | 3000 |
6 | Huang | Beijing | 28 | 2800 |
Table 2: Contact_Info table
Phone_Number | EmpID | Address | Gender |
---|---|---|---|
+1-8054098000 | 2 | Brooklyn, New York, USA | F |
+33-147996101 | 3 | Grenelle, Paris, France | M |
+31-201150319 | 4 | Geuzenveld, Amsterdam, Netherlands | F |
+86-1099732458 | 6 | Yizhuangzhen, Beijing, China | M |
+65-67234824 | 7 | Yishun, Singapore | M |
+81-357799072 | 8 | Koto City, Tokyo, Japan | M |
-
The below SQLite statement returns TRUE and records of female employees from Employee table.
SELECT * FROM Employee WHERE EXISTS (SELECT EmpID FROM Contact_Info WHERE Employee.EmpID = Contact_Info.EmpID AND Gender = 'F');
This will produce the result as shown below:
EmpID Name City Age Salary 2 Marry New York 24 2750 4 Kim Amsterdam 30 3100 -
The below mentioned SQLite statement returns TRUE and records of male employees from Employee table.
SELECT * FROM Employee WHERE EXISTS (SELECT EmpID FROM Contact_Info WHERE Employee.EmpID = Contact_Info.EmpID AND Gender = 'M');
This result of above query will be:
EmpID Name City Age Salary 3 Jo Paris 27 2800 6 Huang Beijing 28 2800
❮ SQLite - Operators