How to subtract 30 days from the current date using SQL Server
To subtract 30 days from the current date in SQL Server, use the DATEADD
function:
Processing different data types
Transforming varchar to datetime
To navigate from varchar
to datetime
, before heading towards date manipulation, use CAST
or CONVERT
:
Or, with CONVERT
:
Note: The style 120
gives us the yyyy-mm-dd hh:mi:ss
(24-hour) format.
Subtracting days from datetime columns
For datetime
columns, as easy as pie:
Advanced cases unravelled
Dealing with a range in days
DATEADD
is super-flexible, capable of manipulating different intervals like hours, months, or years:
Leap year magic
Gotcha! Leap years can add an extra layer of complexity. When subtracting months or years, your result can take a detour:
Addressing timezones
Time-zones giving a headache? Use AT TIME ZONE
to ease the pain:
Common pitfalls
Misplaced data types
Avoid storing date-time values in varchar
. Always choose a date-specific data type - it makes calculations accurate, and life a lot simpler.
Overlooking DST
Watch out for Daylight Saving Time - it may sneakily introduce hour changes. Beware if you're dealing with exact hour calculations.
Unnecessary conversions
DATEADD
is an efficient function, but repeatedly converting varchar
to datetime
can affect performance. Thus, upgrade your data types in the database when time-conscious computations are common.
Was this article helpful?