MySQL BETWEEN Operator

 The BETWEEN operator in MySQL is used in a WHERE clause to select values within a given range. The values can be numbers, text, or dates. It's a shorthand way of using >= and <= for defining a range, enhancing readability and simplicity in your SQL code. 

Syntax 

The basic syntax for the BETWEEN operator in MySQL is:

SELECT column1, column2, ..., columnN 
FROM table_name 
WHERE column_name BETWEEN value1 AND value2;

In this syntax: 

  • column1, column2, ..., columnN: These are the names of the columns you want to select. 
  • table_name: This is the name of the table from which you want to select data. 
  • column_name: This is the name of the column where you are looking for values within a range. 
  • value1 and value2: These define the range within which the column_name values should fall.

Demo Database

To demonstrate the examples, let's consider a demonstration database named SchoolDB with a table of Students. The Students table consists of the following columns: student_idfirst_namelast_namegrade_levelmajor_subject.

Examples

Now, let's see the BETWEEN operator in action: 

Using BETWEEN with Numeric Values 

To select all students who are in grade_level between 10 and 12, inclusive, use:

SELECT * FROM Students WHERE grade_level BETWEEN 10 AND 12;
This statement returns all students who are in 10th, 11th, or 12th grade. 

Using BETWEEN with Date Values 

Assuming there's a birthdate column in the Students table, to find all students born between '2005-01-01' and '2007-12-31', you can use:
SELECT * FROM Students WHERE birthdate BETWEEN '2005-01-01' AND '2007-12-31';
This statement fetches all students born between the start of 2005 and the end of 2007. 

Summary 

The BETWEEN operator in MySQL is a powerful tool when you need to work with ranges in your database queries. It's an effective shorthand for using greater than, less than, or equal to operators, making your SQL code cleaner and easier to read. 

Mastering the BETWEEN operator helps you write more efficient and intuitive queries. It empowers you to handle a wide range of scenarios, from age calculations to period-specific data analyses, enhancing your database management skills.

Comments