SQL GETDATE function is one of the Date and Time Function, which is used to return the Current Date and Time. The return value of this function is derived from the OS (Operating System) of the computer on which the SQL Server instance is running.
In this article we use this Getdate function to find SQL Today’s date with a practical example.
SQL GETDATE Syntax
The basic syntax of the GETDATE function in SQL Server is as follows:
We can use this function to find out:
- When was the data inserted, or updated?
- Maintaining the Log files
- When was the last order, the customer has made?
- How long an Employee associated with us? etc
SQL GETDATE Example 1
The SQL Server GETDATE function returns datetime data type, and the format is: ‘yyyy-mm-dd hh:mm:ss.mmm’ (you can see, fractional seconds precision is 3).
SELECT GETDATE() AS [Current_Date]
SQL GETDATE Function Example 2
In this example, we are going to show you the some of GETDATE examples.
-- SQL Today's date example SELECT 'Today' AS 'TODAY', GETDATE() AS [Current_Date]; SELECT 'Year' AS 'YEAR', DATEPART(year, GETDATE()) AS [Present_Year]; SELECT 'Month' AS 'MONTH', DATENAME(month, GETDATE()) AS [Month_Name]; SELECT 'Tomorrow' AS 'DAY', DATEADD(day, 1, GETDATE()) AS [Next_Day];
We used the SQL DATEPART function to display the year value from today’s date
SELECT 'Year' AS 'YEAR', DATEPART(year, GETDATE()) AS [Present_Year];
We used the SQL DATENAME to display the Month name from today’s date
SELECT 'Month' AS 'MONTH', DATENAME(month, GETDATE()) AS [Month_Name];
Next, we used the SQL DATEADD function to display the Tomorrow date
SELECT 'Tomorrow' AS 'DAY', DATEADD(day, 1, GETDATE()) AS [Next_Day];
Sql Server GETDATE Function Example 3
In this example, we are going to check Employee details (such as: Which date we hired him, how long he associated with this company etc). For this sql today’s date example, we are using SQL DATEDIFF function.
SELECT [FirstName] + ' '+ [LastName] AS [Full Name] ,[Occupation] ,[YearlyIncome] ,[HireDate] ,DATEDIFF (year, [HireDate], GETDATE()) AS [YEARS] ,DATEDIFF (quarter, [HireDate], GETDATE()) AS [QUARTERS] ,DATEDIFF (month, [HireDate], GETDATE()) AS [MONTHS] ,DATEDIFF (day, [HireDate], GETDATE()) AS [DAYS] FROM [SQL Tutorial].[dbo].[Employee]
From the above screenshot, you can observe that, we used the DATEDIFF function to show the difference between the Employee Hire date and Today (GETDTE()). I suggest you refer SQL DATEDIFF function article to understand the above code.
Thank You for Visiting Our Blog