How to Calculate Age From Date of Birth in SQL Server

If you’ve ever tried to calculate someone’s age in SQL Server, you’ve probably run into the same trap most beginners fall into. You call DATEDIFF(), get a number back, and it looks right. But then someone born in December throws the whole thing off by a year.

This happens because DATEDIFF() counts the number of year boundaries crossed between two dates, not the actual number of full years that have passed. It’s a subtle difference, but it matters a lot when you’re dealing with real people’s birthdays.

In this article, we’ll walk through the correct way to calculate age in SQL Server, why the naive approach fails, and a few variations you’ll actually use in production.

Read more

SQL Server Date Formats: Get the Output You Need

You know what you want the date to look like. You just need the SQL to produce it. So instead of starting with functions and working forward, this article starts with formats and works backward. Each heading is a format you might want, with the code to get you there.

All examples use GETDATE() for simplicity. Replace it with your column name and the query works the same way.

Read more

How to Convert a Date to a String in SQL Server

There are a few reasons you might need to convert a date to a string in SQL Server. Maybe you need a date in a specific format for a report. Maybe you’re concatenating it with other text. Maybe an external system expects dates as strings. Whatever the reason, SQL Server gives you several ways to do it, and the right one depends on what you’re trying to achieve.

This article covers four functions: FORMAT(), CONVERT(), CAST(), and STR().

Read more

Fix Error 155 “‘DAYS’ is not a recognized dateadd option” in SQL Server

If you’re getting an error that reads something like “‘DAYS’ is not a recognized dateadd option” in SQL Server, it’s because you’re using the DATEADD() function with an invalid datepart argument.

This often happens when you use a plural form of the argument. For example, DAYS instead of DAY. Or HOURS instead of HOUR.

The easiest way to fix this is to provide a valid datepart argument.

Read more