SQL Cheat Sheet: Dates & Times (SQL Server / T-SQL)
Dates are where SQL queries quietly go wrong.
Ages come out a year too old, weeks start on the wrong day, and empty days vanish from your reports.
This 2-page cheat sheet gives you ready-to-use T-SQL for the date jobs that come up again and again.
What’s inside
- Exact age in years, including why DATEDIFF alone gets birthdays wrong
- Quarter, ISO week number and day of the year
- Start and end of this quarter and last quarter, on any version of SQL Server
- Round dates down to the week, month, quarter or year with DATETRUNC
- Find this Monday, next Monday and this Friday, whatever your DATEFIRST setting
- Weekday or weekend, and counting working days between two dates
- Turn seconds into hh:mm:ss
- The date formats you’ll actually use, with their CONVERT style numbers
- Read UK and US dates correctly with TRY_PARSE
- Build dates and times from separate parts
- Convert UTC to UK time, with BST handled for you
- Build a calendar of dates, and show days with no sales as 0
- A quick guide to date part names and the short forms that catch people out
Who it’s for
- Analysts and developers working with dates in SQL Server
- Anyone building reports by day, week, month or quarter
- Office workers moving from Excel to SQL
Format
A 2-page A4 PDF, ready to print or keep open on a second screen.
Every example uses one fixed date, with the expected result shown beside the query.
For personal use only.
From Rosleecia Productions.