T-SQL 101: 70 Adding and subtracting intervals in SQL Server T-SQL using DATEADD

T-SQL 101: 70 Adding and subtracting intervals in SQL Server T-SQL using DATEADD

When you’re writing T-SQL, you might also need to add intervals to dates, perhaps add days or subtract days and so on. The DATEADD() function is the one that we can add or subtract intervals to the date and time.

Now in the example shown here, what I’ve said is in 20190228 or  28th of February 2019. I want to add on 12 days. To subtract 12 days, I would have just put -12 instead of 12. You can see the output here:

Now there are a wide variety of intervals. It’s not just days. There are values right down to nanosecond.

Notice also though, that there are abbreviations for each of these. So instead of writing day, you could just write d. Or you could write dd, but I’d suggest you don’t do that.

You might imagine that minute is m. But m is actually month and so on, so it can get very confusing. For someone who’s reading your code, it’s much, much better if you actually use the full word. So even words like nanosecond, second or millisecond, just put the whole word.

You’ll see lots of old programming where people have used the abbreviation instead. Don’t follow that.

Learning T-SQL

It’s worth your while becoming proficient in SQL. If you’d like to learn a lot about T-SQL in a hurry, our Writing T-SQL Queries for SQL Server course is online, on-demand, and low cost.

2020-05-18