Getting the current date in SQL Server?
You can get the current date in SQL Server by using GETDATE()
and then trim off the time part using CONVERT()
:
The result is just the today's date, time is not included.
And don't forget, there's a clear separation of roles here. Your database works overtime to store and retrieve data, while display formatting is the job of your application layer.
The midnight-precision approach
Need the compound, date-with-time-but-midnight-precise form? Just ask SQL Server for help:
This code snippet will get you the date of today at midnight. That's right, Cinderella. You can have your own ball every day with SQL Server!
The fine print: other methods and potential traps
Just like a Swiss army knife, SQL Server packs several ways to fetch the current date/time:
SYSDATETIME()
: Gives date and time, with more precision thanGETDATE()
.CURRENT_TIMESTAMP
: The universal SQL way of getting current date and time. It's likeGETDATE()
, but all dressed up.
Remember, though, GETDATE()
tells you the date/time where SQL Server lives, not where you live. If you're in different time zones, you might see some surprising results!
Performance and efficiency
When time (pun entirely intended) is of utmost importance, and you're calling this function more often than your best friend, you need to benchmark different methods. While CAST()
is a good lad and generally efficient, the DATEADD
and DATEDIFF
duo can also prove to be a performance superhero in certain scenarios.
And keep this in mind - even a seemingly simple operation like fetching the date could have an exponential impact on query performance in massive datasets. So always be mindful of your indexing strategy!
Was this article helpful?