BETWEEN Operator in SQL
The BETWEEN operator in SQL is used to filter the result set within a certain range. It selects values within a given range. The values can be numbers, text, or dates. The BETWEEN operator is inclusive, meaning it includes the start and end values.
SQL Syntax
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Examples:1. Using BETWEEN with Numbers: Suppose we have a table Products with the columns ProductID, ProductName, and Price.
SQL
FROM Products
WHERE Price BETWEEN 10 AND 50;
This query selects all products with prices between 10 and 50 (inclusive).
2. Using BETWEEN with Dates: Suppose we have a table Orders with the columns OrderID, OrderDate, and CustomerID.
SQL
FROM Orders
WHERE OrderDate BETWEEN '2023-01-01' AND '2023-12-31';
This query selects all orders placed between January 1, 2023, and December 31, 2023.
3. Using BETWEEN with Text: Suppose we have a table Employees with the columns EmployeeID, FirstName, and LastName.
SQL Syntax
FROM Employees
WHERE LastName BETWEEN 'A' AND 'M';
This query selects all employees whose last names are between 'A' and 'M' (inclusive). Important Notes
- The BETWEEN operator is inclusive; it includes both the start and end values in the range.
- The BETWEEN operator can be used with numbers, text, and dates.
- The ordering of values matters: BETWEEN value1 AND value2 means that value1 should be less than or equal to value2.
Using BETWEEN can make your queries more readable and concise when you're filtering data within a range.