Click here to Skip to main content
15,898,373 members
Articles / DevOps
Tip/Trick

Computing First and Last Day of Current and Previous Month (SQL Server)

Rate me:
Please Sign up or sign in to vote.
2.40/5 (3 votes)
26 Sep 2017CPOL2 min read 22.7K   51   5   13
A quick way to calculate first and last day of curent month and previous month

Introduction

This tip is about getting first and last day of current and previous month, a highly desired requirement in many database and reporting solutions.

There are many examples available but it is always good to explore them further.

SQL2008R2 and previous versions require work around to calculate first and last day of the month. It is very important to keep a consistent approach to calculate the first and last day of the current and previous month.

Despite the fact that SQL2012 and upward versions provide built in EOMONTH() function to calculate first day and last day of month, it is worth considering to understand how to get there without the need to use EOMONTH() because the code can be modified further for related computations.

Logic Behind Code

If you know the logic behind the code, it is relatively easier to understand and write the code.

Get First Day of Current Month

  1. Subtract all days of the current month
  2. Add one day to get first day

Get Last Day of Current Month

  1. Get (same) current day of next month
  2. Subtract all the days of next month

Get First Day of Previous Month

  1. Get previous month
  2. Subtract all days of the previous month
  3. Add one day to get first day

Get Last Day of Previous Month

Subtract all the days of current month

Coding Example

The workaround is to use DateAdd() function to subtract days of month using Day() function according to the requirements as shown below in the coding example:

SQL
--=================================================================================================
-- (1) Get first day of current month
--=================================================================================================
-- Subtract all days of current month
DECLARE @MonthFirstDay DATETIME =_
(SELECT CONVERT(CHAR(15),DATEADD(DD,-DAY(GETDATE()),GETDATE()),106))
 
-- Add one day to get first day
SET @MonthFirstDay=@MonthFirstDay+1
 
-- Show first day of current month
SELECT @MonthFirstDay as MonthFirstDay
--================================================================================================
-- (2) Get last day of current month
--================================================================================================
-- Get (same) current day of next month
DECLARE @MonthLastDay DATETIME=(SELECT CONVERT(CHAR(15),DATEADD(MM,1,GETDATE()),106))
 
-- Subtract all the days of next month
SET @MonthLastDay=DATEADD(DD,-DAY(@MonthLastDay),@MonthLastDay)
 
-- show last day of current month
SELECT @MonthLastDay as MonthLastDay
 
--=================================================================================================
-- (3) Get first day of previous month
--=================================================================================================
-- Get previous month
DECLARE @PrevMonthFirstDay DATETIME =(SELECT CONVERT(CHAR(15),DATEADD(MM,-1,GETDATE()),106))
 
-- Subtract all days of previous month
SET @PrevMonthFirstDay=_
(SELECT CONVERT(CHAR(15),DATEADD(DD,-DAY(@PrevMonthFirstDay),@PrevMonthFirstDay),106))
 
-- Add one day to get first day
SET @PrevMonthFirstDay=@PrevMonthFirstDay+1
 
-- Show first day of previous month
SELECT @PrevMonthFirstDay as PrevMonthFirstDay
 
--=================================================================================================
-- (2) Get last day of previous month
--=================================================================================================
-- Subtract all the days of current month
DECLARE @PrevMonthLastDay DATETIME=_
(SELECT CONVERT(CHAR(15),DATEADD(DD,-Day(GETDATE()),GETDATE()),106))
 
-- show last day of current month
SELECT @PrevMonthLastDay as PrevMonthLastDay

Image 1

Points of Interest

It is recommended to convert these scripts into procedures to avoid repetition of the code and then relying on calling the stored procedures whenever required.

Think of a transactional monthly report where you cannot use built-in function EOMonth() due to version limitation then it is handy to pre-calculate beginning and end of the current month using the above scripts (better if turned into procedures).

References

  1. http://blog.sqlauthority.com/2007/05/13/sql-server-query-to-find-first-and-last-day-of-current-month/
  2. https://sqlmate.wordpress.com/2012/08/24/get-first-and-last-day-of-month-in-sql-2012-and-sql-2008-and-earlier/

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Database Developer
United Kingdom United Kingdom
Haroon's deep interest in logic and reasoning at an early age of his academic career paved his path to become a data professional.

He began his professional life as a computer programmer more than 10 years ago working on his first data venture to migrate and rewrite a public sector database driven examination system from IBM AS400 (DB2) to SQL Server 2000 using VB 6.0 and Classic ASP along with developing reports and archiving many years of data.

His work and interest revolves around Database-Centric Architectures and his expertise include database and reports design, development, testing, implementation and migration along with Database Life Cycle Management (DLM).

Comments and Discussions

 
GeneralMy vote of 3 Pin
Zeleax27-Sep-17 22:33
Zeleax27-Sep-17 22:33 
QuestionEOMONTH Pin
Zeleax27-Sep-17 19:18
Zeleax27-Sep-17 19:18 
AnswerRe: EOMONTH Pin
Haroon Ashraf27-Sep-17 21:59
Haroon Ashraf27-Sep-17 21:59 
QuestionProblems with data type and basic assumptions... Pin
SqlNightOwl27-Sep-17 11:26
professionalSqlNightOwl27-Sep-17 11:26 
AnswerRe: Problems with data type and basic assumptions... Pin
Haroon Ashraf28-Sep-17 1:36
Haroon Ashraf28-Sep-17 1:36 
GeneralRe: Problems with data type and basic assumptions... Pin
SqlNightOwl28-Sep-17 3:32
professionalSqlNightOwl28-Sep-17 3:32 
GeneralRe: Problems with data type and basic assumptions... Pin
Haroon Ashraf28-Sep-17 5:28
Haroon Ashraf28-Sep-17 5:28 
SuggestionWhy not just use the first date of the current month as seed? Pin
Komron Nouri26-Sep-17 9:48
Komron Nouri26-Sep-17 9:48 
GeneralRe: Why not just use the first date of the current month as seed? Pin
Haroon Ashraf26-Sep-17 11:25
Haroon Ashraf26-Sep-17 11:25 
GeneralRe: Why not just use the first date of the current month as seed? Pin
Komron Nouri26-Sep-17 12:04
Komron Nouri26-Sep-17 12:04 
Thank you for your feedback.

I understand in greater detail what you were working to accomplish here.

Please feel free to use my code as needed. Smile | :)

When I teach my students, I typically try to show them to build off of a common point, which is why I mentioned putting forward the first date of the month (which can be stored in a variable instead of just in a CTE or a derived table).

Also, if there is no desire to work with string concatenation (which can be expensive) the following can be used instead:
SQL
Convert(date, DateAdd(day, -Day(GetDate()) + 1, GetDate()))


I suppose building each of them in turn from the ground up, (personally) I would have only introduced the DateAdd() and Day() methods to cut down on what I needed to explain to them. Only because introducing Convert went over some of my students heads when dealing with the different Char() values and the additional style parameter of the Convert method.

SQL
--================================================================================================================
-- (1) Get first day of current month
--================================================================================================================
-- Subtract all days of current month (offset by one)
Declare @MonthFirstDay date = DateAdd(DD, -Day(GetDate()) + 1, GetDate())
 
-- Show first day of current month
Select @MonthFirstDay as MonthFirstDay
--================================================================================================================
-- (2) Get last day of current month
--================================================================================================================
-- Get (same) current day of next month
Declare @MonthLastDay date = DateAdd(MM, 1, GetDate())
 
-- Subtract all the days of next month
Set @MonthLastDay= DateAdd(DD, -Day(@MonthLastDay), @MonthLastDay)
 
-- show last day of current month
Select @MonthLastDay as MonthLastDay
 
--================================================================================================================
-- (3) Get first day of previous month
--================================================================================================================
-- Get previous month
Declare @PrevMonthFirstDay date = DateAdd(MM, -1, GetDate())
 
-- Subtract all days of previous month (offset by one)
Set @PrevMonthFirstDay= DateAdd(DD, -Day(@PrevMonthFirstDay) + 1, @PrevMonthFirstDay)
 
-- Show first day of previos month
Select @PrevMonthFirstDay as PrevMonthFirstDay
 
 
--================================================================================================================
-- (4) Get last day of previous month
--================================================================================================================
-- Subtract all the days of current month
Declare @PrevMonthLastDay date= DateAdd(DD, -Day(GetDate()), GetDate())
 
-- show last day of current month
Select @PrevMonthLastDay as PrevMonthLastDay


But that is just me. I appreciate your article and have already shared it with my students to help them in their own SQL journey's Smile | :)
GeneralRe: Why not just use the first date of the current month as seed? Pin
Haroon Ashraf26-Sep-17 21:44
Haroon Ashraf26-Sep-17 21:44 
QuestionThis is what I use to find the last day of a month Pin
#realJSOP26-Sep-17 8:25
professional#realJSOP26-Sep-17 8:25 
AnswerRe: This is what I use to find the last day of a month Pin
Haroon Ashraf26-Sep-17 11:33
Haroon Ashraf26-Sep-17 11:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.