It can also allow you to create timestamps when a specific record is modified. This article will cover how to add the current date and time using Standard SQL.
Function Syntax
The function has a simple syntax that is easy to use and implement.
An example of syntax usage is shown below:
The previous query should return the current date and time in the defined timezone.
2022-03-18 10:34:59.168105+03
(1 ROW)
NOTE: Although most database engines support the now function, some may miss the feature.
The Standard SQL alternative to the now() function is the current_datetime() function. The syntax is shown below:
The function takes the target timezone as the parameter. The function will use the system’s default if no timezone is specified.
When specifying the timezone, it is best to opt for the timezone name instead of an hour and minute offset.
You can check the timezone names in the resources below:
https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
SQL Extract Part
You may need to extract a specific value from a date in some instances. Using the EXTRACT() method in Standard SQL, you can extract parts, such as:
- Year
- Day of week
- Month
- Quarter
- Week
- Second
- Minute
- Hour
- Millisecond
And many more.
An example is shown below:
This should return the year from the returned DateTime object. An example output is provided below:
---------
2022
(1 ROW)
NOTE: Keep in mind that your database engine may be missing the now function. Opt for current_datetime() if so.
Conclusion
This article covered how to use the SQL now function, current_datetime in standard SQL, and extracting specific units from the result. We hope you found this article helpful. Check the other Linux Hint articles for more tips and tutorials.