COMPUTER ENGINEER

Jump to examples
Blog
SQL Server / T-SQL6 min study
15/ 65

Querying and aggregation

Dates, times and period analysis

Boundaries, time zones and periods.

UnderstandStudy an examplePractise

Understand the concept

DATEADD adds an interval. DATEDIFF counts crossings of the chosen date-part boundary; it is not always elapsed duration. A one-second crossing of New Year can yield 1 for DATEDIFF(year, ...). YEAR and MONTH can create reporting labels.

Rather than wrapping an indexed filter column in YEAR(OrderDate), apply start/end bounds directly to the timestamp. Keep time-zone policy consistent across the application and reports. Current-time functions make exercises change over time, so this course uses fixed 2026 dates.

WHEN TO USE IT

Use it for monthly reporting, date filters and duration calculations.

COMMON PITFALL

Treating DATEDIFF(year) as an exact age, or using an incorrect timestamp end boundary.

01 / PRACTICE

One topic. Three levels of depth.

T-SQL / SQL Server 2019+
SELECT DATEADD(day, 7, CAST('2026-01-05' AS date)) AS NextWeek;

Produces 12 January 2026.

This page does not execute SQL. Practise in the downloadable SqlStudioLab using SSMS. Before rerunning temporary-table examples, remove only the relevant #table. Views, procedures and functions create persistent lab objects; never use a production connection.

02 / YOUR TURN

Try it yourself first.

Retrieve April orders with a half-open interval.

Show the solution and explanation
Worked solution
SELECT OrderId FROM lab.SalesOrder WHERE OrderDate >= '2026-04-01' AND OrderDate < '2026-05-01';

Returns 109, 110, 111 and 112.