How can I select the first day of a month in SQL?
Here's your go-to solution to swiftly get the first day of the current month in multiple SQL environments:
- SQL Server:
- Oracle:
- MySQL:
✔️ Each of these queries returns the first day of the current month—directly usable in your SQL contexts.
Dynamic date manipulation
Sometimes, you're not just interested in the current month. You might have a particular date, @mydate
, and you need to know the start of the month for that date. With SQL Server, we can leverage the DATEADD
and DATEDIFF
functions for precise date calculations:
Here, the literal 0
corresponds to the base date (1900-01-01
), yielding the first day of @mydate's
month.
Less coding, more functionality
Let's walk away from those hardcoded and less maintainable dates. From SQL Server 2012 and onward, we've been blessed with the DATEFROMPARTS
and EOMONTH
functions. They simplify date calculations and totally skip manual string manipulation:
Utilizing these built-in functions guarantees slim margin of error and peak performance.
In the wild: Different SQL ecosystems
Working with multiple SQL databases calls for adaptability. A look at how to get the first day of the current month in common SQL environments:
- We've seen SQL Server's
DATEFROMPARTS
andEOMONTH
functions in action. - Oracle, has the mighty
TRUNC
function. - MySQL utilizes
DATE_FORMAT
and the helpfulLAST_DAY
function:
- PostgreSQL users can rely on
DATE_TRUNC
:
Understanding your toolset across SQL preferences takes you a notch higher in writing versatile and scalable code.
Was this article helpful?