🔥 Articles, eBooks, Jobs, Columnist, Forum, Podcasts, Courses 🎓

Getting the last 120 months of data from my database | ecode10.com


Getting the last 120 months of data from my database

how to do it in SQL language?

sql

To retrieve data for the last 120 months from a given datetime column in SQL, you can use date functions available in your specific SQL dialect (e.g., SQL Server, MySQL, PostgreSQL, Oracle).

The general approach involves calculating the date 120 months ago and then filtering records that are newer than or equal to that calculated date.

Here's how you can achieve this in different SQL systems:

1 - SQL Server

	SELECT *
		FROM YourTable
	WHERE YourDateTimeColumn >= DATEADD(month, -120, GETDATE());
  • GETDATE() returns the current date and time.
  • DATEADD(month, -120, GETDATE()) subtracts 120 months from the current date.

2 - MySQL:

SELECT *
	FROM YourTable
WHERE YourDateTimeColumn >= DATE_SUB(CURDATE(), INTERVAL 120 MONTH);
  • CURDATE() returns the current date.
  • DATE_SUB(CURDATE(), INTERVAL 120 MONTH) subtracts 120 months from the current date.

3 - PostgreSQL:

SELECT *
	FROM YourTable
WHERE YourDateTimeColumn >= (CURRENT_DATE - INTERVAL '120 months');
  • CURRENT_DATE returns the current date.
  • INTERVAL '120 months' specifies a time interval of 120 months to subtract.

4 - Oracle:

SELECT *
	FROM YourTable
WHERE YourDateTimeColumn >= ADD_MONTHS(SYSDATE, -120);
  • SYSDATE returns the current date and time.
  • ADD_MONTHS(SYSDATE, -120) subtracts 120 months from the current date.

Important Considerations:

Replace YourTable and YourDateTimeColumn with the actual name of your table and the datetime column you are filtering on.

Time Component: The examples above typically filter based on the date part. If you need to include records from the exact start of the 120-month period, ensure your YourDateTimeColumn also includes a time component or adjust the calculation accordingly (e.g., by setting the time of the calculated start date to midnight).

Specific Date vs. Current Date: If you need to get the last 120 months relative to a specific date instead of the current date, replace GETDATE(), CURDATE(), CURRENT_DATE, or SYSDATE with your desired specific date value.





Related articles




Top