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.
That's it.
You may also like to read:
How to Edit More than 200 rows in SQL Server
Window functions in sql server
Find nth highest salary in SQL Server
How to Select LAST N Row in SQL Server
How to get the records of last month using sql query in SQL server?