← Back to Chapters

MySQL IN

? MySQL IN

? Quick Overview

The IN operator allows you to specify multiple values in a WHERE clause. It is a concise shorthand for multiple OR conditions and can accept literals or a subquery result set.

? Key Concepts

  • Purpose: Match a column value against a list of possible values.
  • Flexibility: Values can be numbers, strings, or produced by a subquery.
  • Readability: Cleaner than chained OR expressions.
  • Case sensitivity: MySQL string comparisons are case-insensitive by default for typical collations.

? Syntax / Theory

? View Code Example
-- Syntax for IN: select specific columns where a column matches any value in the list
SELECT column1, column2, ...
FROM table_name
WHERE column_name IN (value1, value2, ...);

? Code Example(s)

? View Code Example
-- Select students who belong to either 'Science' or 'Engineering' departments
SELECT * FROM students
WHERE department IN ('Science', 'Engineering');

-- Select employees with specific IDs
SELECT * FROM employees
WHERE employee_id IN (1001, 1003, 1005);

? Live Output / Explanation

Explanation

  • IN: Tests whether a value equals any value in a list. Equivalent to multiple OR checks.
  • Subqueries: You can use IN (SELECT ...) to compare against a set returned from another query.
  • Performance: For very large lists, consider joins or temporary tables; for moderate lists, IN is readable and efficient.

✅ Tips & Best Practices

  • Use IN for filtering against a short list of known values (IDs, categories).
  • Prefer joins or indexed temporary tables for very large sets returned by subqueries.
  • Ensure string literals are quoted to avoid syntax errors.
  • Remember NOT IN behaves differently with NULL values — be cautious.

? Try It Yourself / Practice Tasks

  • Write a query to find all employees whose departments are either 'HR' or 'Sales'.
  • Use IN to find all students who have taken any of the courses 'Math', 'History', or 'Physics'.
  • Experiment with a subquery: WHERE id IN (SELECT user_id FROM subscriptions WHERE active=1).