SQL Standard

SQL Now Function

The NOW function in SQL allows you to get the current date and time. It is a handy function that will enable you to add the accurate date and time to your database records.

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:

SELECT NOW();

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:

SELECT CURRENT_DATETIME([timezone]);

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:

  1. Year
  2. Day of week
  3. Month
  4. Quarter
  5. Week
  6. Second
  7. Minute
  8. Hour
  9. Millisecond

And many more.

An example is shown below:

SELECT EXTRACT(YEAR FROM now());

This should return the year from the returned DateTime object. An example output is provided below:

EXTRACT
---------
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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list