In a database, timestamps are most common for determining when a record is added or updated.
This article will discuss using Standard SQL to get the current timestamp, current date, and current DateTime.
SQL Current Timestamp
Let’s discuss how to get the current timestamp in Standard SQL. For this, we can use the current_timestamp function.
The syntax is as shown:
The function should then return the current timestamp when the query is executed on the server.
NOTE: The timestamp returned by the function is continuous, non-ambiguous, and has exactly 60 seconds per minute.
An example use case is shown below:
CURRENT_TIMESTAMP() AS now;
This should return the timestamp as shown:
SQL Current DateTime
You can also get the current date and time that a query is executed using the current_datetime function.
The syntax is as shown:
The function takes the target timezone and returns the date-time for that timezone. If the timezone is not specified, the result will be in UTC.
An example usage is as shown:
CURRENT_DATETIME() as utc,
CURRENT_DATETIME('Africa/Nairobi') AS nairobi,
CURRENT_DATETIME('+03:00') as utc_add;
We use three different techniques to specify the timezones in the example above.
"nairobi": "2022-03-18T21:30:39.619901"
"utc_add": "2022-03-18T21:30:39.619901"
SQL Current Date
Using the current_date function, you can also get the current date in the specified timezone using the current_date function. An example usage is as shown:
CURRENT_DATE() as utc,
CURRENT_DATE('Africa/Nairobi') AS nairobi,
CURRENT_DATE('+03:00') as utc_add;
The code above should return the output as shown:
"nairobi": "2022-03-18"
"utc_add": "2022-03-18"
The above returns date type.
Conclusion
This article explores how to get the current timestamp, current DateTime, and date-time in Standard SQL. Learn more about SQL through other articles in this website.