Sling Academy
Home/Node.js/How to Select Records Between Two Dates in Sequelize

How to Select Records Between Two Dates in Sequelize

Last updated: December 29, 2023

Introduction

Sequelize is a powerful Object-Relational Mapping (ORM) library for Node.js. It provides a high-level abstraction for dealing with databases in a Node.js environment. One of the common tasks when working with databases is selecting records based on date ranges. In this tutorial, we will learn how to select records that fall between two specific dates using Sequelize.

We will start with the basics of date comparison and gradually move towards more complex scenarios, including querying with time zones and handling different database dialects. Whether you are just getting started with Sequelize or looking to brush up on specific querying techniques, this guide will provide you with the code examples you need to effectively select data within a date range.

Basic Date Range Selection

To begin, we will look at how to perform a basic query to select records between two dates. Assume we have a model called Event, with a date field named startDate.

const { Op } = require('sequelize');
const startDate = new Date('2023-01-01');
const endDate = new Date('2023-01-31');
Event.findAll({
    where: {
        startDate: {
            [Op.between]: [startDate, endDate]
        }
    }
});

This query will return all Event records where the startDate falls within January 2023.

Advanced Selection with Timezones

Handling dates with time zones can be tricky. Sequelize allows you to specify the time zone in your configuration. For querying, you need to be aware of how your dates are stored in the database and convert your dates to the appropriate time zone if necessary.

// Suppose your dates are stored in UTC and you want to query in EST
c     const startDateUTC = new Date('2023-01-01T00:00:00Z');
const endDateUTC = new Date('2023-01-31T23:59:59Z');
Event.findAll({
    where: {
        startDate: {
            [Op.between]: [startDateUTC, endDateUTC]
        }
    }
});

This will adjust the time range to query by the UTC time zone, ensuring accuracy across different locales.

Working with Different Databases

Sequelize supports various databases such as PostgreSQL, MySQL, SQLite, and MSSQL. Date handling can vary slightly across these databases, so it’s important to be aware of any quirks. Sequelize does a good job of abstracting most of these differences, but always verify the behavior with your specific database version and timezone settings.

Conclusion

In this tutorial, we’ve learned the basic to advanced techniques to select records between two dates in Sequelize, considering time zones, and database dialect specifics. By mastering these querying skills, you’ll be better equipped to handle temporal data effectively in your Node.js applications. Remember that accurate date querying is crucial for the integrity and reliability of your application, so always test your queries thoroughly.

Next Article: Mastering the LIKE Condition in Sequelize.js

Previous Article: How to Execute Raw SQL Queries in Sequelize

Series: Sequelize.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates