How do you use the GETDATE function to get the current date and time?
Posted by HenryPk
Last Updated: June 05, 2024
In SQL Server, the GETDATE() function is used to obtain the current date and time. When you call GETDATE(), it returns a datetime value representing the current system date and time. Here’s how you use the GETDATE() function: 1. Basic Usage: You can simply select the result of the GETDATE() function in a SQL query.
SELECT GETDATE() AS CurrentDateTime;
This will return a single result set with the current date and time. 2. Inserting Data: You can use GETDATE() when inserting records into a table to set a timestamp.
INSERT INTO YourTable (Column1, Column2, CreatedAt)
VALUES ('Value1', 'Value2', GETDATE());
3. Using in a WHERE Clause: You can use it in filtering records based on the current date and time.
SELECT *
FROM YourTable
WHERE CreatedAt >= GETDATE() - 30; -- Get records from the last 30 days
4. Formatting: If you need a specific format or only the date or time part, you can use other functions in combination with GETDATE(). For example, to get just the current date without the time component, you can cast it:
SELECT CAST(GETDATE() AS DATE) AS CurrentDate;
5. Date Calculations: You can also perform calculations using GETDATE(). For example, to add days, subtract hours, etc.
SELECT GETDATE() AS CurrentDateTime,
       DATEADD(DAY, 5, GETDATE()) AS DateAfter5Days;
Overall, GETDATE() is a straightforward and commonly used function in SQL Server for retrieving the current date and time.
Related Content