# A guide to SQL Between Operator

**URL:** <https://forum.freecodecamp.org/t/a-guide-to-sql-between-operator/290664>\
**Category:** freeCodeCamp Contributors\
**Tags:** guide\
**Created:** [June 30, 2019, 3:20am UTC](https://forum.freecodecamp.org/t/a-guide-to-sql-between-operator/290664 "2019-06-30T03:20:37Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![camperbot](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/camperbot/32/18364_2.png) [@camperbot](https://forum.freecodecamp.org/u/camperbot)\
**Post date:** [June 30, 2019, 3:20am UTC](https://forum.freecodecamp.org/t/a-guide-to-sql-between-operator/290664/1 "2019-06-30T03:20:38Z")

</div>

The BETWEEN Operator is useful because of the SQL Query Optimizer. Although BETWEEN is functionally the same as: x \<= element \<= y, the SQL Query Optimizer will recognize this command faster, and has optimized code for running it.

This operator is used in a WHERE clause or in a GROUP BY HAVING clause.

Rows are selected that have a value greater than the minimum value and less than the maximum value.

It’s important to keep in mind that the values entered in the command are **excluded** from the result. We get just what is between them.

Here is the syntax for using the function in a WHERE Clause:

```auto
select field1, testField
from table1
where testField between min and max

```

Here is an example using the student table and the WHERE clause:

```auto
-- no WHERE clause
select studentID, FullName, studentID
from student;
    
-- WHERE clause with between
select studentID, FullName, studentID
from student
where studentID between 2 and 7;

```

![image-1](https://freecodecamp.s3.amazonaws.com/guide-sql-images/between01.JPG?raw=true)

Here is an example using the campaign funds table and the having clause. This will return rows where the sum of the donations for a candidate are between $3 Million and $18 Million based on the HAVING clause in the GROUP BY part of the statement. More on aggregation in that guide.

```auto
select Candidate, Office_Sought, Election_Year, format(sum(Total_$),2)
from combined_party_data
where Election_Year = 2016
group by Candidate, Office_Sought, Election_Year
having sum(Total_$) between 3000000 and 18000000
order by sum(Total_$) desc; 

```

![image-1](https://freecodecamp.s3.amazonaws.com/guide-sql-images/between02.JPG?raw=true)

---

<div class="post-metadata">

**Author:** ![ILM](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/ilm/32/363239_2.png) [@ILM](https://forum.freecodecamp.org/u/ILM)\
**Post date:** [January 8, 2025, 4:01pm UTC](https://forum.freecodecamp.org/t/a-guide-to-sql-between-operator/290664/2 "2025-01-08T16:01:08Z")

</div>

Closed on January 8, 2025, 4:01pm UTC


