SQL stands for Structured Query Language. SQL is used for retrieving useful information from a large set of data and it is used for storing the data in the Database, modifying, or manipulating the data from the database.
In this article, we are going to discuss IN Operator and EXISTS Operator in SQL as well as the difference between these two operators in detail.
IN Operator in SQL
To match an expression against a list of values, SQL provides the IN Operator. So we do not need to use multiple OR conditions in SELECT, UPDATE, and other statements. You can list values directly or provide a query result to the IN operator.
Syntax:
SELECT columnName(s)
FROM tableName
WHERE columnNameX IN (value1,vaule2,....);
Parameters:
columnName(s)
: The columns to retrieve data from.tableName
: The name of the table from which to retrieve data.columnNameX
: The column to compare against the list of values.value1, value2, ...
: The list of values to check against.
Example
Suppose we have a table named "Customers" as:
Query
CREATE table Customer(
CUSTOMERID INT PRIMARY KEY,
FIRST_NAME VARCHAR(50),
LAST_NAME VARCHAR(50),
AGE INT);
INSERT INTO Customer(CUSTOMERID,FIRST_NAME,LAST_NAME,AGE) VALUES
(1,'Mohit','Kumar',21),
(2,'Praful','Singh',22),
(3,'Ritik','Kumar',25),
(4,'Vishnu','Yadav',26);
Output
Customer TableNow we want to see the details of the customers whose FIRST_NAME can be 'Mohit' or 'Praful' or 'Ritik', we can use IN operator & give a set of values to check upon.
Query
SELECT * FROM Customer where FIRST_NAME IN('Mohit', 'Praful', 'Ritik');
Output
outputExists Operator in SQL
If the argument sub-query is non-empty, exists construct returns the value true, otherwise false. To check whether a row is returned through this sub-query or not, it is used. True is returned if one or more rows are returned by executing the sub-query, otherwise False when no rows are returned.
Syntax
SELECT columnName(s) FROM tableName1
WHERE EXISTS (subquery);
Parameters:
columnName(s)
: The columns to retrieve data from.tableName1
: The main table from which to retrieve data.subquery
: A subquery that returns a set of values.
The sub-query is a SELECT statement. The EXISTS condition will be met & it will return TRUE if the subquery returns at least one record in its result set, else, the EXISTS condition will not be met and it will return FALSE.
Example
Now, let up suppose we have another table: "Accounts"
Create Accounts table
CREATE table Accounts(
CUSTOMERID INT PRIMARY KEY,
ACCNO INT,
ACCTYPE VARCHAR(50))
INSERT INTO Accounts(CUSTOMERID,ACCNO,ACCTYPE) VALUES
(1,101,'Savings'),
(2,102,'Savings'),
(3,103,'Savings'),
(4,104,'Current');
Output
Accounts TableNow to see all the customers whose any kind of account exists, we can make use of exists keyword as:
Query
SELECT * FROM Customer WHERE EXISTS(SELECT * FROM Accounts
WHERE Customer.CUSTOMERID=Accounts.CUSTOMERID);
Output
outputWe here check: match for every CUSTOMERID in the customer table with the CUSTOMERID in the accounts table.
If Customer.CUSTOMERID = Accounts.CUSTOMERID evaluates to be true in the sub-query, and one row is returned & thus the sub-query evaluates to be true & our outer query (Select * from Customer) gets, executed for that particular customer.
Note: To do the same thing, i.e. to see all the customers whose any kind of account exists, we can make use of IN keyword also.
Query
SELECT * FROM Customer
WHERE CUSTOMERID IN (SELECT CUSTOMERID FROM Accounts);
Output
outputIN Vs EXISTS Operators
IN Operator | EXISTS Operator |
---|
IN can be used as a replacement for multiple OR operators. | To determine if any values are returned or not, we use EXISTS. |
Faster execution as subquery executes only once. | Slower execution as EXISTS Operator forces the sub-query to execute again & again for each subsequent outer Query. |
In the IN-condition SQL Engine compares all the values in the IN Clause. | Once true is evaluated in the EXISTS condition then the SQL Engine will stop the process of further matching. |
Follow BOTTOM - UP Approach of execution. | Follow TOP-DOWN Approach of execution. |
The IN operator cannot compare anything with NULL values. | The EXISTS clause can compare everything with NULLs. |
A direct set of values can be given for comparison. | Cannot compare directly the values, a sub-query needs to be given. |
Conclusion
In this article, we have basically mentioned the IN and EXISTS operator and the differences between them. Both the operators, whether the IN and EXISTS, play an important role in the Structured Query language. IN operator is used to reduce the OR conditions, whereas EXISTS operator is used to look for the existence of a row in a given table that satisfies a set of criteria or not. The main characteristic of the IN operator is its following BOTTOM-UP approach for execution. There are some differences between their functions, IN operator can not be compared to anything with NULL values but EXISTS can compare with NULL values.
Similar Reads
MySQL IN vs. EXISTS
In MySQL, We have two commonly used clauses in SQL queries that are EXISTS and IN used for querying data efficiently for high-performance applications. EXISTS and IN are the two most important clauses that are used to filter and extract data from the database. Although they both use subqueries in th
4 min read
NOT IN vs NOT EXISTS in SQL
Structured Query Language (SQL) is a domain-specific language used in managing and manipulating data in a relational database. In SQL, we use these two operators i.e. NOT IN and NOT EXISTS to filter out and efficiently retrieve our data from a table. Both of these operators are negations of IN and E
5 min read
NOT IN vs NOT EXISTS in PL/SQL
PL/SQL is a Procedural Language/Structured Query Language. It allows developers to create robust, modular, and reusable code for implementing data manipulation, and transaction control in databases. Two crucial operators in PL/SQL are NOT IN and NOT EXISTS, which are often used to filter data based
5 min read
NOT IN vs NOT EXISTS in PostgreSQL
PostgreSQL is one of the most advanced general-purpose object-relational database management systems and is open-source. Being an open-source software, its source code is available under the PostgreSQL license, a liberal open-source license. Anyone with the right skills can use, modify, and distribu
4 min read
SQL | EXISTS
The SQL EXISTS condition is used to test whether a correlated subquery returns any results. If the subquery returns at least one row, the EXISTS condition evaluates to TRUE; otherwise, it evaluates to FALSE. The EXISTS operator can be used in various SQL statements like SELECT, UPDATE, INSERT, and D
3 min read
Truncate Table if Exists in SQL
When managing databases it is common to encounter scenarios where we need to remove all the data from a table while preserving the table structure. The TRUNCATE statement is a popular SQL command used for this purpose. However, what happens if the table we want to truncate doesnât exist? Executing a
3 min read
How to Insert Row If Not Exists in SQL
Managing and manipulating data in SQL is essential, especially when it comes to avoiding duplicate entries in a database. Duplicate records can lead to data inconsistencies and errors that disrupt operations and analysis. The "INSERT IF NOT EXISTS" feature in SQL acts as a safeguard, ensuring that o
6 min read
PL/SQL EXISTS Operator
The EXISTS operator in PL/SQL is a powerful tool used to check the existence of records in a subquery. Unlike traditional comparison operators that evaluate data values, EXISTS focuses on whether a set of conditions returns any rows. It is commonly used to determine the presence or absence of record
6 min read
NULL values in SQL
In SQL, some records in a table may not have values for every field, and such fields are termed as NULL values. These occur when data is unavailable during entry or when the attribute does not apply to a specific record. To handle such scenarios, SQL provides a special placeholder value called NULL
4 min read
Having vs Where Clause in SQL
In SQL, filtering data is important for extracting meaningful insights from large datasets. While both the WHERE and HAVING clauses allow us to filter data, they serve distinct purposes and operate at different stages of the query execution process. Understanding the difference between these clauses
4 min read