Sling Academy
Home/SQLite/How to Use BETWEEN for Range Queries in SQLite

How to Use BETWEEN for Range Queries in SQLite

Last updated: December 07, 2024

When working with databases, performing range queries efficiently is a common need. SQLite, one of the most popular database engines, provides an elegant solution to perform such queries using the BETWEEN operator. In this article, we will explore how you can leverage BETWEEN in SQLite for performing range queries.

Understanding the BETWEEN Operator

The BETWEEN operator allows you to specify a range to filter results. It is inclusive, meaning that the boundary values are included in the result set. The syntax for using BETWEEN is as follows:

SELECT column1, column2, ... 
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

In this syntax, value1 and value2 represent the range boundaries and should be of the same data type as column_name.The BETWEEN clause will filter the result set to include only those records where column_name has a value within the specified range.

Applying the BETWEEN Operator

Let's consider an example to understand how the BETWEEN operator functions. Suppose we have a table named employees storing employee details including a salary column. We want to find employees whose salary is between $50,000 and $100,000.

CREATE TABLE employees (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    title TEXT NOT NULL,
    salary INTEGER NOT NULL
);

INSERT INTO employees (name, title, salary) VALUES
('Alice', 'Developer', 55000),
('Bob', 'Manager', 75000),
('Carol', 'CEO', 150000),
('David', 'HR', 95000);

To use BETWEEN to find employees whose salary lies within the specified range, you can run the following query:

SELECT name, salary
FROM employees
WHERE salary BETWEEN 50000 AND 100000;

The above SQL command will return 'Alice', 'Bob', and 'David' because their salaries fall within the range of $50,000 to $100,000.

Working with Date Ranges

The BETWEEN operator is not limited to numerical data and can be exceptionally useful with dates. Assume you have a sales table containing transaction dates. You want to pull records from January 2023:

CREATE TABLE sales (
    id INTEGER PRIMARY KEY,
    product_name TEXT NOT NULL,
    sale_date DATE NOT NULL
);

INSERT INTO sales (product_name, sale_date) VALUES
('Product A', '2023-01-05'),
('Product B', '2023-01-15'),
('Product C', '2023-02-10'),
('Product D', '2023-01-25');

Here is how to query for sales within January 2023:

SELECT product_name, sale_date
FROM sales
WHERE sale_date BETWEEN '2023-01-01' AND '2023-01-31';

This query will fetch 'Product A', 'Product B', and 'Product D' as they occurred in January 2023.

Using NOT BETWEEN for Exclusion

Similar to BETWEEN, SQLite also supports NOT BETWEEN for selecting records outside a certain range. For example, if you want to exclude employees whose salary is between $50,000 and $100,000:

SELECT name, salary
FROM employees
WHERE salary NOT BETWEEN 50000 AND 100000;

This SQL statement returns the employee 'Carol', as her salary does not fall within the defined range.

Best Practices

  • Ensure the data types of values used with BETWEEN match that of the column to avoid unintended results.
  • Take advantage of indexing for columns frequently used in range queries to enhance performance. SQLite automatically handles indexing on primary keys but consider explicitly indexing other columns used in BETWEEN conditions if performance is an issue.

By using the BETWEEN operator, you can efficiently perform range queries in SQLite across various data types, making it a powerful tool in your querying arsenal.

Next Article: Making Queries Simpler with IN in SQLite

Previous Article: Filtering Data in SQLite Using the WHERE Clause

Series: CRUD Operations in SQLite

SQLite

You May Also Like

  • How to use regular expressions (regex) in SQLite
  • SQLite UPSERT tutorial (insert if not exist, update if exist)
  • What is the max size allowed for an SQLite database?
  • SQLite Error: Invalid Value for PRAGMA Configuration
  • SQLite Error: Failed to Load Extension Module
  • SQLite Error: Data Type Mismatch in INSERT Statement
  • SQLite Warning: Query Execution Took Longer Than Expected
  • SQLite Error: Cannot Execute VACUUM on Corrupted Database
  • SQLite Error: Missing Required Index for Query Execution
  • SQLite Error: FTS5 Extension Malfunction Detected
  • SQLite Error: R-Tree Node Size Exceeds Limit
  • SQLite Error: Session Extension: Invalid Changeset Detected
  • SQLite Error: Invalid Use of EXPLAIN Statement
  • SQLite Warning: Database Connection Not Closed Properly
  • SQLite Error: Cannot Attach a Database in Encrypted Mode
  • SQLite Error: Insufficient Privileges for Operation
  • SQLite Error: Cannot Bind Value to Parameter
  • SQLite Error: Maximum String or Blob Size Exceeded
  • SQLite Error: Circular Reference in Foreign Key Constraints