Write SQL Query for Specific Date Range and Date Time



Filtering data by date or datetime is a common requirement when working with SQL queries. Whether you're retrieving records for a specific date, a range of dates or precise timestamps SQL provides robust tools to handle such scenarios.

Understanding Date and DateTime Data Types

The SQL databases support various data types for storing the date and time information:

  • DATE: Stores only the date (e.g. 2025-01-07).
  • DATETIME: The Stores both date and time (e.g. 2025-01-07 14:30:00).
  • TIMESTAMP: The Stores date and time with time zone information in some databases.
  • TIME: The Stores only the time (e.g. 14:30:00).

Knowing the data type of the column you're working with is crucial for writing accurate queries.

Syntax for Filtering by Date

To filter records for a specific date range we use the WHERE clause with comparison operators or SQL functions.

Common Operators for Date Filters

  • =: Matches a specific date.
  • > or <: Filters dates greater than or less than a given value.
  • >= or <=: Includes the given date in the range.
  • BETWEEN: Filters records within a range inclusive of the boundaries.

Example Queries :

1. Query for a Specific Date

To retrieve records for January 1, 2025:

SELECT *
FROM Orders
WHERE OrderDate = '2025-01-01';

2. Query for a Date Range

To retrieve records between January 1, 2025, and January 7, 2025:

SELECT *
FROM Orders
WHERE OrderDate BETWEEN '2025-01-01' AND '2025-01-07';

This includes records on both 2025-01-01 and 2025-01-07.

3. Query for Dates Greater Than or Less Than a Specific Date

To retrieve records after January 1, 2025:

SELECT *
FROM Orders
WHERE OrderDate > '2025-01-01';

To retrieve records before January 1, 2025:

SELECT *
FROM Orders
WHERE OrderDate < '2025-01-01';

4. Query Using Date Functions

Some databases allow functions for extracting parts of the date: To retrieve records for January 2025:

SELECT *
FROM Orders
WHERE YEAR(OrderDate) = 2025 AND MONTH(OrderDate) = 1;

Filtering by DateTime

1. Query for a Specific Date and Time

To retrieve records for January 1, 2025, at exactly 14:30:

SELECT *
FROM Orders
WHERE OrderDateTime = '2025-01-01 14:30:00';

2. Query for a DateTime Range

To retrieve records between January 1, 2025, 14:00 and January 2, 2025, 18:00:

SELECT *
FROM Orders
WHERE OrderDateTime BETWEEN '2025-01-01 14:00:00' AND '2025-01-02 18:00:00';

3. Query for DateTime Greater Than or Less Than a Specific Value

To retrieve records after January 1, 2025, at 12:00:

SELECT *
FROM Orders
WHERE OrderDateTime > '2025-01-01 12:00:00';
Updated on: 2025-01-27T17:54:29+05:30

120 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements