To retrieve the current date and time in SQL, I use built-in date functions β the exact function name can vary slightly depending on the database system.
In most cases, the common ones are:
GETDATE()in SQL ServerCURRENT_TIMESTAMP(ANSI standard β works in most databases like SQL Server, MySQL, PostgreSQL, Oracle)SYSDATEin OracleNOW()in MySQL and PostgreSQL
For example, in SQL Server I can simply write:
SELECT GETDATE() AS CurrentDateTime;
This returns both the current date and time from the system clock of the database server.
If I need only the current date, I can convert or cast it like this:
SELECT CAST(GETDATE() AS DATE) AS CurrentDate;
And for only the time part:
SELECT CAST(GETDATE() AS TIME) AS CurrentTime;
In one of my audit logging projects, I used GETDATE() to automatically capture when each record was inserted or updated β for example:
INSERT INTO AuditLog (UserID, Action, LogTime)
VALUES (101, 'Record Updated', GETDATE());
This helped track user activity accurately.
A challenge Iβve faced is dealing with time zone differences β since GETDATE() or NOW() usually returns the serverβs local time. To handle that, I often use GETUTCDATE() (in SQL Server) or CURRENT_TIMESTAMP AT TIME ZONE 'UTC' to standardize time across different regions.
So, in summary β
- Use
GETDATE()orNOW()(depending on the database) to get the current date and time. - Use conversions to get only date or time if needed.
- And be mindful of time zones in distributed systems.
