SQL BETWEEN Operator

The SQL BETWEEN operator is used to filter the result set within a specific range. It is often used with WHERE clauses to select values within a range, such as numbers, dates, or text.

The BETWEEN operator is inclusive, meaning it includes the boundary values.

In this tutorial, we will go through SQL BETWEEN Operator, its syntax, and how to use this operator in SQL statements, with the help of well detailed examples.


Syntax of SQL BETWEEN Operator

The basic syntax of the SQL BETWEEN operator is as follows:

</>
Copy
SELECT column1, column2, ...
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

Each part of this syntax has a specific purpose:

  • SELECT: Specifies the columns to retrieve.
  • FROM: Specifies the table from which to retrieve data.
  • WHERE column_name BETWEEN value1 AND value2: Filters the rows where column_name is between value1 and value2, inclusive of both boundary values.

Step-by-Step Examples with MySQL

We’ll go through various examples demonstrating the BETWEEN operator in MySQL. Using MySQL 8.0 with MySQL Workbench, we’ll use a sample students table with fields id, name, age, grade, and locality.

Setup for Examples: Creating the Database and Table

1. Open MySQL Workbench and create a new database:

</>
Copy
CREATE DATABASE school;

2. Select the school database:

</>
Copy
USE school;

3. Create a students table:

</>
Copy
CREATE TABLE students (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50),
    age INT,
    grade VARCHAR(10),
    locality VARCHAR(50)
);

4. Insert sample data into the students table:

</>
Copy
INSERT INTO students (name, age, grade, locality)
VALUES
('Alice', 14, '8th', 'Northside'),
('Bob', 15, '9th', 'Westend'),
('Charlie', 14, '8th', 'Northside'),
('David', 16, '10th', 'Southend'),
('Eva', 15, '9th', 'Westend');