While working with SQL Server database tables, we may want to run query to get records of last quater or you can say get records of last 3 months in SQL Server using Datetime column, so in this article, I have mentioned how we can do this in SQL Server with an example.
Let's consider we have below SQL Server and we want to get only last 3 months data from it:
Then we can use
DATEADD() function in SQL Server.
DateAdd() function has below syntax
DATEDADD(DatePart, increment/decrement (int), expression (date))
where, DatePart = The part of date to which DATEADD adds an integer number, like Month, Date or year.
int = An expression that can resolve to an int that DATEADD adds to a datepart of date.
date = valid date or datetime value.
Considering above table and DateAdd function, we can have below query to get 3 months records in SQL Server
SELECT * FROM [OrderDetails].[dbo].[Order] WHERE OrderDate >= DATEADD(MONTH, -3, GETDATE())
Which will return rows which has OrderDate of last 3 months.
In the above query DateAdd as 3 parameters:
Month = which denotes, we will compare value with Month.
-3 = Number of months to deduct.
GetDate = returns today's date.
Once you will execute above query, you will see output as below:
As you can see from above output, only 3 rows are returned which has OrderDate created within 3 months.
We can also modify above query to return last 90 days records in SQL Server
SELECT * FROM [OrderDetails].[dbo].[Order] WHERE OrderDate >= DATEADD(DAY, -90, GETDATE())
Output would be same as above.
You may also like to read: