Introduction to IN Condition
The IN condition is a logical condition which is used in queries to specify a range of values. It is commonly used in the WHERE clause of a SELECT, UPDATE, DELETE, or MERGE statement to filter rows based on a specific list of values.With the help of IN condition we can can make queries more simple and readable when dealing with multiple values or subqueries.
Syntax:
query...
IN (subquery/value_list)
query...
Example 1
Let’s find out all employees who have an odd employee_id.
Query:
SELECT * FROM employees
WHERE employee_id IN
(
SELECT employee_id FROM employees
WHERE employee_id%2=1
);
Output:
Explanation: In the above query, We have fetched the information about all employees who have an odd employee_id.
Example 2
Let’s fetch the information about all the employees whose name starts with A.
Query:
SELECT * FROM employees
WHERE employee_id IN
(
SELECT employee_id FROM employees
WHERE employee_name LIKE 'A%'
);
Output:
Explanation: In the above query we have fetched the information related all the employees whose name starts with A.
Example 3
Let’s finds out all the employee which have a manager assigned to them.
Query:
SELECT * FROM employees
WHERE employee_id IN
(
SELECT employee_id FROM employees
WHERE manager_id IS NOT NULL
);
Output:
Explanation: In the above query, We have fetched the information related all the employee which have a manager assigned to them.
Difference Between EXISTS and IN 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. In this article, we will learn about the EXISTS and IN Condition, various examples, and their differences too in PostgreSQL.