Date functions in MS SQL Server allow you to extract specific parts of a date, perform arithmetic between two timestamps, and format date values for reporting. To use these functions, you simply need a database instance with a table containing date-related data types such as DATE, DATETIME, DATETIME2, or SMALLDATETIME, and the necessary permissions to execute SELECT queries.
What You'll Need
- SQL Server Management Studio (SSMS) or Azure Data Studio.
- Access to a SQL Server database.
- A table with at least one date or time column to practice with.
Step-by-Step
- Retrieve the Current System Date and Time:
The most common starting point is getting the current timestamp. Use
GETDATE()to return the current date and time of the operating system on which the instance of SQL Server is running. If you need higher precision, useSYSDATETIME(), which returns a datetime2 value.
Example:SELECT GETDATE() AS CurrentDateTime; - Extract Specific Components from a Date:
When you need only the year, month, or day from a full timestamp, use the specific extraction functions. These are essential for grouping data by month or year in reports.
YEAR(date): Returns the integer year.MONTH(date): Returns the integer month (1-12).DAY(date): Returns the day of the month.
Example:SELECT YEAR(OrderDate), MONTH(OrderDate) FROM Sales.Orders; - Calculate the Difference Between Two Dates:
The
DATEDIFF()function is the primary tool for finding the span of time between two dates. It requires three arguments: the date part (e.g., day, month, year, hour), the start date, and the end date.
Example: To find how many days have passed since an order was placed:SELECT DATEDIFF(day, OrderDate, GETDATE()) AS DaysElapsed FROM Sales.Orders; - Add or Subtract Time from a Date:
Use
DATEADD()to move a date forward or backward. Like DATEDIFF, it requires a date part, a number to add (use negative numbers to subtract), and the original date.
Example: To find a date 30 days in the future:SELECT DATEADD(day, 30, GETDATE()) AS DueDate; - Format Dates into Strings:
The
FORMAT()function allows you to turn a date into a human-readable string based on a specific culture or custom pattern. While powerful, note that it is slower thanCONVERT()for very large datasets.
Example:SELECT FORMAT(GETDATE(), 'dd-MM-yyyy') AS FormattedDate; - Convert Date Types for Compatibility:
Use
CAST()orCONVERT()to change a DATETIME to a DATE (removing the time portion).CONVERT()is specifically useful because it allows for style codes to define the output format.
Example:SELECT CONVERT(date, GETDATE()) AS DateOnly; - Find the Start and End of a Period:
To truncate a date to the beginning of the month or year, you can use
DATETRUNC()(available in newer versions of SQL Server) or a combination ofDATEADDandDATEDIFF.
Example:SELECT DATETRUNC(month, GETDATE()) AS StartOfMonth;
Common Mistakes
One of the most frequent errors is confusing the order of arguments in DATEDIFF(). SQL Server calculates EndDate - StartDate. If you place the more recent date first, you will receive a negative number, which can break logic in WHERE clauses or application code.
Another common pitfall is using FORMAT() in the SELECT list of a query that processes millions of rows. Because FORMAT() relies on the .NET CLR, it is significantly slower than CONVERT(). For high-performance reporting, always prefer CONVERT() with a style code (like 101 for US or 103 for UK formats).
Developers often forget that GETDATE() returns the server's local time. In distributed applications where users are in different time zones, this leads to data inconsistency. In these cases, GETUTCDATE() should be used to ensure a universal standard across all records.
Finally, avoid performing date arithmetic by adding integers directly to dates (e.g., OrderDate + 7). While this works for the older DATETIME type, it is not supported for the newer DATE or DATETIME2 types. Always use DATEADD() for compatibility and clarity.
Tips
To optimize queries that filter by date, avoid wrapping your table columns in functions within the WHERE clause. For example, instead of writing WHERE YEAR(OrderDate) = 2023, use a range: WHERE OrderDate >= '2023-01-01' AND OrderDate < '2024-01-01'. This allows SQL Server to use an index on the OrderDate column (SARGability), drastically improving performance.
When dealing with dates that might be null, use ISNULL() or COALESCE() to provide a default date. This prevents your calculations from returning NULL, which can often lead to empty reports or application crashes.
If you frequently need to find the last day of the month, use EOMONTH(). This function simplifies the logic significantly compared to the old method of adding one month and subtracting one day.
For those working with complex time zones, investigate the AT TIME ZONE clause. It allows you to convert a timestamp from one time zone to another without manually calculating offsets, which is crucial for handling Daylight Savings Time changes.
Troubleshooting
If you encounter an "out-of-range" error when inserting or querying a date, check the data type of the column. The SMALLDATETIME type only supports dates from 1900-01-01 to 2079-06-06. If your data falls outside this range, you must alter the column to DATETIME2, which supports dates from 0001-01-01 to 9999-12-31.
If your date formatting looks strange (e.g., the month and day are swapped), check your session's LANGUAGE or DATEFORMAT settings. You can explicitly set this for your session using SET DATEFORMAT mdy; or SET LANGUAGE 'English'; to ensure the server interprets string literals correctly.
When DATEDIFF() returns a value that seems off by one, remember that it counts the number of boundary crossings. For example, DATEDIFF(year, '2023-12-31', '2024-01-01') returns 1 because a year boundary was crossed, even though only one day passed. If you need precise duration, calculate the difference in days and divide by 365.25.
If a query is running extremely slowly on a date-filtered table, check the execution plan in SSMS. If you see an "Index Scan" instead of an "Index Seek," it is likely because you are using a function on the column in the WHERE clause. Remove the function and use a date range to restore performance.
Frequently Asked Questions
How do I get only the date from a DATETIME column?
The most efficient way is to use CAST(column_name AS DATE) or CONVERT(DATE, column_name). This strips the time portion and returns only the date.
What is the difference between GETDATE() and CURRENT_TIMESTAMP?
There is no functional difference. CURRENT_TIMESTAMP is the ANSI SQL standard equivalent of GETDATE(). Using it makes your code more portable to other database systems.
How can I find the last day of the current month?
Use the EOMONTH(GETDATE()) function. It returns the last date of the month for the date provided in the argument.
How do I add 6 months to a date?
Use DATEADD(month, 6, YourDateColumn). This will correctly handle the transition between years.
Can I convert a string to a date?
Yes, use TRY_CAST('2023-12-25' AS DATE) or TRY_CONVERT(DATE, '2023-12-25'). Using the "TRY" version is safer because it returns NULL instead of an error if the string is not a valid date.
How do I find the day of the week?
Use DATEPART(weekday, YourDateColumn). Note that the result depends on the @@DATEFIRST setting, which determines which day of the week is considered the first day.