PostgreSQL IN
The IN
operator checks if a given value matches any value in a list or subquery. It’s more concise and often faster than multiple OR
conditions.
Key Topics
1. Basic Usage
SELECT first_name, department
FROM employees
WHERE department IN ('Sales', 'Marketing', 'HR');
This returns rows where department
is Sales, Marketing, or HR.
2. Using Subqueries
SELECT first_name, department
FROM employees
WHERE department IN (SELECT dept_name FROM departments WHERE location = 'NY');
The subquery returns valid departments in NY, and employees matching those departments are retrieved.
Best Practices
- Use
IN
for cleaner queries compared to multipleOR
statements. - Optimize subqueries with indexes to enhance performance.
Key Takeaways
IN
provides a concise way to match a value against multiple options.- Subqueries with
IN
can dynamically filter based on another table's results.