Get the last day of the month in SQL
If you're here for a quick way to get the last day of the month, here's how:
Using the EOMONTH
function in SQL:
For those on the pre-SQL Server 2012 squad, use DATEADD
and DATEDIFF
to subtract a day from the first of the next month:
Mastering the calculations
In some cases, you'll have to go beyond the basics. Let's break down these scenarios:
Dealing with leap years
Leap years throw extra party (day) to February. The EOMONTH
function handles leap years without breaking a sweat.
Code uncluttering with variable assignment
For readable and reusable code, consider storing the date in a variable:
Jumping over the months
EOMONTH
allows you to peer into the future or past months. The second parameter is your time machine:
Visualization
Understanding these functions is a cinch when visualized:
Crunching the numbers: Performance talk
Performance matters, especially with large datasets. Here's the lowdown:
-
EOMONTH
is your speed demon 🏎️ - efficient for large datasets. -
The
DATEADD
andDATEDIFF
workaround is like an old reliable pickup 🚛 - more verbose, but gets you there.
Rolling back the SQL Server years
For users stuck in the SQL Server 2008 time-capsule or earlier, DATEADD
comes to your rescue:
This method avoids any scary string manipulation or casting. Phew!
Juggling different date requirements
The solution is adaptable for diverse date requirements in your databases. Smoothly switch from GETDATE()
to other source date forms.
Was this article helpful?