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

SQL Server CONVERT() Date Style Codes Explained (With Examples)

In SQL Server, dates are stored in one format but often need to be displayed in another. That’s where the CONVERT() function can help. It lets you take a date value and turn it into a string in whatever format you need, whether that’s MM/DD/YYYY for an American audience or DD-MM-YYYY for a universally recognized date format.

The tricky part when using this function is the style code. This a number you pass into CONVERT() that tells it which format to use. There are dozens of style codes, and they’re not exactly intuitive to memorise. This article breaks down the most useful ones with real examples so you can find what you need and move on.

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