T-SQL 101: 72 Extracting date and time components in SQL Server T-SQL using DATEPART

T-SQL 101: 72 Extracting date and time components in SQL Server T-SQL using DATEPART

In previous posts, I mentioned that you can easily extract the year, month, and day from dates and times, but you might want other components. That’s what the DATEPART() function does.

You can see the output from the query above here:

To use this function , we put the interval that we’re after and then the value we want to find it out from. So if you look at this one, I said I wanted the day from 28th of February 2019. The day is 28.

If we look at second example, I had a date there, but I had no time shown at all, so the second comes up as zero.

In the third example, I did have seconds shown, so that was 11 hours, 59 minutes and 46 seconds. It’s then extracted the 46 seconds out.

It’s a useful function.

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-06-01