PostgreSQL BETWEEN
Summary: in this tutorial, you will learn how to use the PostgreSQL BETWEEN operator to check if a value falls in a particular range of values.
Introduction to the PostgreSQL BETWEEN operator
The BETWEEN
operator allows you to check if a value falls within a range of values.
The basic syntax of the BETWEEN
operator is as follows:
If the value
is greater than or equal to the low
value and less than or equal to the high
value, the BETWEEN
operator returns true
; otherwise, it returns false
.
You can rewrite the BETWEEN
operator by using the greater than or equal ( >=
) and less than or equal to ( <=
) operators and the logical AND operator:
If you want to check if a value is outside a specific range, you can use the NOT BETWEEN
operator as follows:
The following expression is equivalent to the expression that uses the NOT BETWEEN
operators:
In practice, you often use the BETWEEN
operator in the WHERE clause of the SELECT, INSERT, UPDATE, and DELETE statements.
PostgreSQL BETWEEN operator examples
Let’s take a look at the payment
table in the sample database.
1) Using the PostgreSQL BETWEEN operator with numbers
The following query uses the BETWEEN
operator to retrieve payments with payment_id
is between 17503
and 17505
:
Output:
2) Using the PostgreSQL NOT BETWEEN example
The following example uses the NOT BETWEEN
operator to find payments with the payment_id
not between 17503
and 17505
:
Output:
3) Using the PostgreSQL BETWEEN with a date range
If you want to check a value against a date range, you use the literal date in ISO 8601 format, which is YYYY-MM-DD
.
The following example uses the BETWEEN
operator to find payments whose payment dates are between 2007-02-15
and 2007-02-20
and amount more than 10:
Output:
Summary
- Use the
BETWEEN
operator to check if a value falls within a particular range. - Use the
NOT BETWEEN
operator to negate theBETWEEN
operator.