I need a query to retrieve records from the Sales
table for the last 7 days. Can someone provide the SQL query for this?
How to Write a Query to Get Data from the Last 7 Days in SQL Server?
15816-Jul-2024
Updated on 16-Jul-2024
Home / DeveloperSection / Forums / How to Write a Query to Get Data from the Last 7 Days in SQL Server?
I need a query to retrieve records from the Sales
table for the last 7 days. Can someone provide the SQL query for this?
Ravi Vishwakarma
16-Jul-2024To retrieve data from the last 7 days in SQL Server, you can use the
GETDATE()
function along with theDATEADD()
function to filter the rows.Here's a simple example of how to achieve this:
Assume you have a table named
Users
with a columnCreationDate
that stores the date and time when each order was placed.Query to Get Data from the Last 7 Days
Explanation
GETDATE()
: This function returns the current date and time.DATEADD(day, -7, GETDATE())
: This function subtracts 7 days from the current date and time. It essentially calculates the date and time exactly 7 days ago.OrderDate >= DATEADD(day, -7, GETDATE())
: This condition filters the rows to include only those where theCreationDate
is within the last 7 days.