What is the purpose of the 'IN' operator in SQL?

Instruction: Explain how the IN operator is used in SQL queries and provide an example of its use.

Context: This question tests the candidate's knowledge of the IN operator, used to specify multiple possible values for a column in WHERE clauses.

Updated

Official answer

IN tests membership in a list or a single-column subquery. It often expresses several equality alternatives clearly:

SELECT customer_id, region
FROM customers
WHERE region IN ('East', 'West')
ORDER BY customer_id;

This includes either listed region. Repeating a value in the list does not multiply result rows. A NULL region does not pass this filter.

NULLs require care. For a nonmatching value, value IN ('East', NULL) is unknown rather than false, so NOT IN can also fail to return expected unmatched rows. Use a correctly correlated NOT EXISTS when that expresses the intended anti-match semantics, and define outer NULL handling separately.

Bind list elements with the driver's supported mechanism; a comma-separated string is not automatically several bound values. Handle an empty application list deliberately because IN () is not valid in many dialects. IN is not inherently faster than equivalent alternatives; compare actual plans when performance matters.

Related Questions