SQL Between
SQL Between
This page covers SQL Between.
The “between” operator is part of the logical operators.
As the name suggests, the operator “between” retrieves data between a given range of values.
The keyword is “between” and the statement requires start and end values. Both values are included.
For more information on operators here.
Let’s use the table “student_info” from the previous tutorials.
id | firstName | lastName | age |
---|---|---|---|
1 | John | Smith | 21 |
2 | Patrick | Casey | 26 |
3 | Sam | Adams | 19 |
4 | Mike | Garcia | NULL |
5 | Patrick | Dumont | 21 |
Between
“Between” works well with the “where” statement.
The following is an example of the “between” logical operator.
SELECT * FROM student_info WHERE age BETWEEN 15 AND 25;
The above statement selects all students, with the filter of age between 15 and 25 years old.
Let’s see the result.
id | firstName | lastName | age |
---|---|---|---|
1 | John | Smith | 21 |
3 | Sam | Adams | 19 |
5 | Patrick | Dumont | 21 |
Not Between
The operator “between” can also be combined with the logical operator “not”.
The combination reverses the effect of the filter, meaning it displays records outside of the given range.
Below is an example of the “not between” combination.
SELECT * FROM student_info WHERE age NOT BETWEEN 15 AND 25;
The outcome outputs one student.
id | firstName | lastName | age |
---|---|---|---|
2 | Patrick | Casey | 26 |
The filter above retrieves all student data that is not within the range of values. In other words, all students that are not 15 years old or 25 years old, or anything between those 2 values.
Next: SQL In