BETWEEN (MySQL Conditions)
In MySQL, the BETWEEN operator is used to select values within a specified range. In this tutorial, we'll discuss the syntax, examples, and usage of the BETWEEN operator in MySQL.
Syntax
The syntax for the BETWEEN operator is as follows:
column_name BETWEEN value1 AND value2
Here, column_name
is the name of the column you want to search, value1
is the lower bound of the range, and value2
is the upper bound of the range.
Example
Let's say we have a table called employees
with columns id
, name
, and salary
. We want to select all employees whose salary is between 30000 and 50000:
SELECT * FROM employees WHERE salary BETWEEN 30000 AND 50000;
This will return all rows from the employees
table where the salary
column is between 30000 and 50000.
Output
When we run the example query above, we will get the following output (depending on the contents of our employees
table):
| id | name | salary |
|----|----------|--------|
| 1 | John Doe | 40000 |
| 3 | Jane Doe | 45000 |
| 5 | Bob Smith| 35000 |
This output shows all the rows in the employees
table where the salary
column is between 30000 and 50000.
Explanation
The BETWEEN operator selects all rows where the value of the specified column is between the lower bound (value1
) and upper bound (value2
) specified in the query. In the example above, we selected all rows from the employees
table where the salary
column was between 30000 and 50000.
Use
The BETWEEN operator is useful when you want to search for values within a specific range. This can be used to filter data in a table based on a certain criteria (such as salary, age, etc.).
Important Points
- The BETWEEN operator is inclusive, which means that the values at the lower and upper bounds of the range are included in the search results.
- The BETWEEN operator can be used with any data type, including numbers, strings, and dates.
- You can use the NOT BETWEEN operator instead of BETWEEN to select all rows outside of a specified range.
Summary
In this tutorial, we discussed the syntax, examples, and usage of the BETWEEN operator in MySQL. The BETWEEN operator is useful when you want to select rows within a specified range of values for a particular column, and it offers a straightforward way to filter a table based on a specific criteria.