BETWEEN Condition

Course- PostgreSQL >

This PostgreSQL tutorial explains how to use the PostgreSQL BETWEEN condition with syntax and examples.

Description

The PostgreSQL BETWEEN condition is used to retrieve values within a range in a SELECT, INSERT, UPDATE, or DELETE statement.

Syntax

The syntax for the BETWEEN condition in PostgreSQL is:

expression BETWEEN value1 AND value2;

Parameters or Arguments

expression

A column or calculation.

value1 and value2

These values create an inclusive range that expression is compared to.

Note

  • The PostgreSQL BETWEEN condition will return the records where expression is within the range of value1 and value2 (inclusive).

Example - With Numeric

Let's look at some PostgreSQL BETWEEN condition examples using numeric values. The following numeric example uses the BETWEEN condition to retrieve values within a numeric range.

For example:

SELECT *

FROM employees

WHERE employee_id BETWEEN 200 AND 300;

This PostgreSQL BETWEEN example would return all rows from the employees table where the employee_id is between 200 and 300 (inclusive). It is equivalent to the following SELECT statement:

SELECT *

FROM employees

WHERE employee_id >= 200

AND employee_id <= 300;

Example - With Date

Next, let's look at how you would use the PostgreSQL BETWEEN condition with Dates.

The following date example uses the BETWEEN condition to retrieve values within a date range.

For example:

SELECT *

FROM employees

WHERE start_date BETWEEN '2014-04-01' AND '2014-04-30';

This PostgreSQL BETWEEN condition example would return all records from the employees table where the start_date is between April 1, 2014 and April 30, 2014 (inclusive). It would be equivalent to the following SELECT statement:

SELECT *

FROM employees

WHERE start_date >= '2014-04-01'

AND start_date <= '2014-04-30';

Example - Using NOT Operator

The PostgreSQL BETWEEN condition can also be combined with the NOT operator. Here is an example of how you would combine the BETWEEN condition with the NOT Operator.

For example:

SELECT *

FROM employees

WHERE employee_id NOT BETWEEN 500 AND 599;

This PostgreSQL BETWEEN example would return all rows from the employees table where the employee_id was NOT between 500 and 599, inclusive. It would be equivalent to the following SELECT statement:

SELECT *

FROM employees

WHERE employee_id < 500

OR employee_id > 599;