SQL Query to Get Last 3 Months Records in SQL Server

← PrevNext →

In SQL Server, the DATEADD() function can be used to retrieve records from the last 3 months (or any number of months you specify). In a previous tutorial, I have shown how to use this function to fetch previous month records. Now in this tutorial, I'll extend that example and show you how to query data from the last three months in SQL Server.

Syntax

The DATEADD() function returns a date time (smalldatetime).

DATEDADD(interval, increment (int), expression (date))

This function is commonly used in date and time related queries.

Parameters

interval: The date and time interval to add. It can be "year", "month" (or M), "day" etc. This is required.
increment (in): An integer value (a number) of interval to add to the date. This is required.
expression (date): A date value.

Example:

SELECT DATEADD(M, 3, GETDATE()) as Three_months_from_now -- Get the 3rd month from the current month.

Now, let's see how we can get the last 3 months records (in a Table) using DATEADD() function.

Create a Table

Let us assume, I have an employee table with few records in it. The table has a date column (the last column). See the image.

Note: Adjust or update the dates in the table (see the image below), to get proper result.

Get last 3 months Records in SQL Server

Query to get Last 3 Months Records

SELECT *FROM Employee
WHERE JoiningDate >= DATEADD(M, -3, GETDATE())

The Output

Showing Last 3 Months Records in SQL Server

Its a one line query. The function DATEADD() takes 3 parameters.

1) The first parameter is the M, which denotes a month. You can replace the M with the MONTH. Like this,

SELECT *FROM Employee
WHERE JoiningDate >= DATEADD(MONTH, -3, GETDATE())

2) The second parameter is "increment" (an integer value or a number). I am using -3 to get the last 3 months records or data. You can use -5, -4 or any number, depending upon your requirement.

💡 Thought you should know: You can use a variable to specify a number, and use the variable inside the DATEADD() function. Like this,

DECLARE @D INT
SET @D = 3
SELECT DATEADD(M, @D, GETDATE())

3) The third parameter inside the DATEADD() function, is an expression or date. I am using the "GETDATE()" function for current month.

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

🔎 Find more related examples.

← PreviousNext →