Forum

"How to Get Last 3 ...
 
Share:
Notifications
Clear all

"How to Get Last 3 Months Data in SQL with Different Date Functions"

1 Posts
1 Users
0 Reactions
1,077 Views
Posts: 134
Admin
Topic starter
(@sql-admin)
Reputable Member
Joined: 6 years ago

Retrieving data from the last three months is a common requirement in real-world SQL reporting and analytics. Whether you're working with sales data, user logs, or transactions, filtering based on dynamic date ranges helps you automate your queries efficiently without hardcoding specific dates.

Most modern SQL databases support powerful date functions that make this task straightforward. Here’s how you can retrieve records from the last 3 months based on a date_column.

SQL Server Example:

SELECT *
FROM orders
WHERE date_column >= DATEADD(MONTH, -3, GETDATE());

In the above query:

  • GETDATE() returns the current system date.

  • DATEADD(MONTH, -3, GETDATE()) subtracts 3 months from the current date.

  • The WHERE clause ensures that only records from the last 3 months are fetched.

MySQL Example:

SELECT *
FROM orders
WHERE date_column >= CURDATE() - INTERVAL 3 MONTH;

CURDATE() returns today’s date, and subtracting a 3-month interval gives the desired range. MySQL automatically handles months with varying numbers of days.

Oracle Example:

SELECT *
FROM orders
WHERE date_column >= ADD_MONTHS(SYSDATE, -3);

In Oracle, SYSDATE returns the current date and time, and ADD_MONTHS() shifts the date backward by 3 months.

PostgreSQL Example:

SELECT *
FROM orders
WHERE date_column >= CURRENT_DATE - INTERVAL '3 months';

PostgreSQL’s interval system is very flexible and allows for clear and readable syntax.


This kind of query is especially useful for building dashboards, generating rolling reports, or automating data pipelines where you want to see only the most recent quarter’s worth of data. Instead of changing the date filter every month manually, you let SQL calculate it dynamically.

Additionally, you can combine this filter with ORDER BY, GROUP BY, or aggregations like SUM, COUNT, and AVG to create powerful summaries.

 


Leave a reply

Author Name

Author Email

Title *

 
Preview 0 Revisions Saved
Share: