Have you ever tried using the DateAdd function to subtract a day from a date, only to end up with unexpected results? You’re not alone. I’ve been there too.
In this post, I’ll share a common pitfall that might be causing the issue and provide a simple solution to get you back on track.
## The Problem
Let’s say you want to find out what the temperature was on the previous day. You try using the DateAdd function to subtract one day from the current date. Sounds straightforward, right? But for some reason, the result isn’t what you expected.
## The Culprit: DateAdd’s Syntax
The DateAdd function takes three arguments: the date part to manipulate (e.g., day, month, year), the number of intervals to add, and the date to operate on. Here’s the catch: the second argument should be a negative number if you want to subtract a day.
For example, if you want to subtract one day from the current date, you should use
DateAdd(day, -1, GETDATE())
. Easy peasy, right?
## Why Datediff Won’t Help (This Time)
You might be thinking, “Hey, I can use the Datediff function to achieve the same result.” And you’re right, you can. But in this case, DateAdd is a more intuitive choice because it allows you to specify the exact date part you want to manipulate.
## Takeaway
So, the next time you’re struggling with the DateAdd function, double-check your syntax and make sure you’re using a negative number to subtract a day. It’s a simple mistake, but one that can save you a lot of frustration.
—
*Further reading: [DateAdd (Transact-SQL)](https://docs.microsoft.com/en-us/sql/t-sql/functions/dateadd-transact-sql?view=sql-server-ver15)*