Retrieve Last 5 Minutes of Data in SQL Server: 3 Efficient Query Examples

← PrevNext →

Assume you have a Sales table in your SQL Server database with a column named "SalesDate" of type DATETIME. Typically, you might use this date column to fetch records from the last three months or similar data. However, this time you need to retrieve data from the last 5 minutes. In this article, I will show you three different SQL queries to accomplish this efficiently.

Here's the Sales table, for example.

CREATE TABLE dbo.Sales_2025(
    SalesID INT PRIMARY KEY NOT NULL,
    Quantity INT NULL,
    Price NUMERIC (18, 2) NULL,
    SalesDate DATETIME NULL
)

Insert some data into it. Now lets retrieve data (or records) that were inserted in the last five minutes.

Query 1: Using DATEADD() and GETDATE() methods

The 1st query gets records that were inserted into the table from the last 5 minutes by comparing the "SalesDate" column with the current time minus 5 minutes.

SELECT * FROM dbo.Sales_2025
WHERE SalesDate >= DATEADD(minute, -5, GETDATE());

See DATEADD() function syntax, parameters and usages in detail.

Note: The DATEADD() function is also supported by Azure SQL Database.

Query 2: Using CURRENT_TIMESTAMP function with DATEADD() method

The 2nd query uses the CURRENT_TIMESTAMP function to get records from the last 5 minutes.

SELECT * FROM dbo.Sales_2025
WHERE SalesDate >= DATEADD(minute, -5, CURRENT_TIMESTAMP);

The CURRENT_TIMESTAMP function returns the current date and time, in a 'YYYY-MM-DD hh:mm:ss.mmm' format.

Syntax

CURRENT_TIMESTAMP

You can use the CURRENT_TIMESTAMP function like this in SQL Server:

SELECT CURRENT_TIMESTAMP

Query 3: Using SYSDATETIME() function with DATEADD() method

The 3rd query retrieves last 5 minutes records by using the SYSDATETIME() function, which returns the current date and time including the functional seconds.

SELECT * FROM dbo.Sales_2025
WHERE SalesDate >= DATEADD(minute, -5, SYSDATETIME());

SYSDATETIME() is a built-in function in SQL Server that returns the current date and time (where SQL Server in running), including fractional seconds. It provides higher precision (nanoseconds) compared to the GETDATE() function. The returned value is of the datetime2 data type.

Syntax

SYSDATETIME()

You can use the SYSDATETIME() function in a query like this in SQL Server:

SELECT SYSDATETIME() AS CurrentDateTime

Compare and contrast the differences (or similarities) in the results from these three queries.

SELECT CURRENT_TIMESTAMP;
SELECT SYSDATETIME();
SELECT GETDATE();

🔎 Find more related examples.

-------------------

🚀 More SQL Tips

How to find employees who were hired in the last n months?
How to edit more than 200 rows in SQL Server Management Studio?
Can an SQL query contain both "where and having" clause?



← PreviousNext →