PostgreSQL BETWEEN

The BETWEEN operator is used to filter rows within a certain range, typically numeric values, dates, or timestamps. It includes the boundary values by default.

Key Topics

1. Numeric Range

SELECT first_name, salary
FROM employees
WHERE salary BETWEEN 40000 AND 60000;

This returns employees with salaries in the [40,000 – 60,000] range.

2. Date Range

You can also use BETWEEN for date or timestamp filtering:

SELECT order_id, order_date
FROM orders
WHERE order_date BETWEEN '2024-01-01' AND '2024-12-31';

This returns orders placed within the specified date range.

Best Practices

  • Ensure data types match (e.g., comparing date to date, numeric to numeric).
  • Use appropriate indexes on columns involved in BETWEEN for performance.

Key Takeaways

  • BETWEEN is inclusive of boundary values.
  • Ideal for quick range queries on numeric or date columns.