PostgreSQL CLOCK_TIMESTAMP() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL CLOCK_TIMESTAMP()
function to return the current date and time.
Introduction to the PostgreSQL CLOCK_TIMESTAMP() function
The CLOCK_TIMESTAMP()
function returns the current date and time with a timezone.
Here’s the basic syntax of the CLOCK_TIMESTAMP()
function:
The CLOCK_TIMESTAMP()
function has no parameters.
The CLOCK_TIMESTAMP()
function returns the current date and time as a timestamp with a timezone.
When you call the CLOCK_TIMESTAMP()
function multiple times within a statement, you’ll get different results.
PostgreSQL CLOCK_TIMESTAMP() function examples
Let’s take some examples of using the CLOCK_TIMESTAMP()
function.
1) Basic CLOCK_TIMESTAMP() function example
The following example uses the CLOCK_TIMESTAMP()
function to obtain the current date and time:
Output:
The result is a timestamp with a time zone.
2) Calling CLOCK_TIMESTAMP() function multiple times within a statement
The following example calls the CLOCK_TIMESTAMP()
function multiple times within a statement:
Output:
The output shows that the CLOCK_TIMESTAMP()
function returns the actual date and time between the calls within the same statement.
3) Using the CLOCK_TIMESTAMP() function to measure the execution time of a statement
First, define a new function called time_it
to measure the execution time of a statement:
Second, use the time_it()
function to measure the execution time of the statement that uses the pg_sleep()
function:
Output:
It takes about 1008 ms or 1s to complete.
Summary
- Use the
CLOCK_TIMESTAMP()
function to return the current date and time.