MySQL IN and BETWEEN β Powerful Filtering Techniques
When you need to filter data based on multiple values or a range of values, MySQL provides two incredibly handy operators: IN
and BETWEEN
.
In this tutorial, we’ll explore how to use IN and BETWEEN in practical scenarios using employees
and departments
tables.
π What is MySQL IN
?
The IN
operator allows you to check if a value matches any value in a list of values.
β Syntax
π§ͺ Examples Using IN
1οΈβ£ Find Employees in Department IDs 2, 4, and 7
π’ Result: Returns all employees who belong to departments 2, 4, or 7.
2οΈβ£ Find Employees with Designations ‘Manager’, ‘Analyst’, ‘HR’
π’ Result: Returns employees with specific job roles.
3οΈβ£ Find Departments Named βSalesβ, βITβ, or βMarketingβ
π’ Result: Returns only those departments that match the list exactly.
4οΈβ£ Combine with NOT
π’ Result: Excludes employees from departments 3 and 5.
π What is MySQL BETWEEN
?
The BETWEEN
operator is used to filter results within a specific range. It works for numbers, dates, and even text (alphabetical order).
β Syntax
π Note: BETWEEN
is inclusive, meaning it includes both value1
and value2
.
π§ͺ Examples Using BETWEEN
1οΈβ£ Find Employees with Salaries Between 30,000 and 50,000
π’ Result: Returns employees whose salaries fall within that range.
2οΈβ£ Find Employees Who Joined Between Two Dates
π’ Result: Filters employees who joined during the year 2023.
3οΈβ£ Find Departments with IDs Between 1 and 5
π’ Result: Returns department records with IDs from 1 to 5.
β
Combine IN
and BETWEEN
in One Query
π’ Result: Returns employees from selected departments whose salary falls in the specified range.
π§ Summary Table
Operator | Use Case | Example |
---|---|---|
IN |
Match any value in a list | WHERE dept_id IN (2, 4, 5) |
BETWEEN |
Match value within a range | WHERE salary BETWEEN 30k AND 5 |
π Real-World Tips (From Acesoftech Academy)
-
Prefer
IN
over multipleOR
conditions β itβs cleaner and easier to maintain. -
When using
BETWEEN
with dates, always use ISO format (YYYY-MM-DD
). -
Combine both to write powerful, concise filters for dashboards and reports.
π Conclusion
Both IN
and BETWEEN
are must-have tools in your MySQL toolbox. Whether you’re selecting multiple specific values or filtering based on a range, these operators help make your queries shorter and more readable.
Try these queries on your own employees
and departments
tables β and build your SQL skills one query at a time!