Open In App

PostgreSQL – CURRENT_TIMESTAMP Function

Last Updated : 20 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

PostgreSQL provides the ‘CURRENT_TIMESTAMP() function, which returns the current date and time, along with the time zone, at the precise moment the transaction begins. This function is often used for tracking the creation or modification of records in a database.

Here, we’ll look into the syntax, usage, and examples of the CURRENT_TIMESTAMP() function to help you better understand how to leverage it in your PostgreSQL database.

CURRENT_TIMESTAMP() Function in PostgreSQL

The CURRENT_TIMESTAMP() function returns the current date and time with time zone information from when the transaction started. It’s important to note that the timestamp reflects the time at the beginning of the transaction, not when the function is called. This feature is particularly useful when you need consistent timestamps for all operations within a single transaction.

Syntax:

CURRENT_TIMESTAMP(precision)

Parameters:

  • The precision is used to set the number of digits in the fractional seconds precision in the second field of the returned query results. If passes without the precision, it returns the current time (TIMESTAMP type value) that includes the full fractional seconds precision available.

Return Value:

  • The CURRENT_TIMESTAMP() function returns a TIMESTAMP WITH TIME ZONE that represents the date and time at which the transaction started.

PostgreSQL CURRENT_TIMESTAMP Function Examples

Let us take a look at some of the examples of CURRENT_TIMESTAMP Function in PostgreSQL to better understand the concept.

Example 1: Basic Usage of CURRENT_TIMESTAMP()

The following statement depicts the use of the CURRENT_TIMESTAMP() function to query for the current date and time:

SELECT CURRENT_TIMESTAMP;

Output:

PostgreSQL CURRENT_TIMESTAMP Function Examples

Explanation: In this example, the timestamp includes the full precision of fractional seconds, along with the time zone.

Example 2: Creating a Table with CURRENT_TIMESTAMP as the Default Value

First create a table named note that has the ‘created_at’ column is a TIMESTAMP WITH TIME ZONE column.

CREATE TABLE note(
note_id serial PRIMARY KEY,
message varchar(255) NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

The ‘created_at’ column gets its default value from the result of the CURRENT_TIMESTAMP() function. Now, insert some data in the table:

INSERT INTO note(message) 
VALUES('Testing current_timestamp function');

Third, verify whether the insert has been taken place correctly using the following query:

SELECT * FROM note;

Output:

PostgreSQL CURRENT_TIMESTAMP Function Example

Explanation: In this output, you can see that the ‘created_at’ column correctly reflects the timestamp when the row was added.



Next Article

Similar Reads

three90RightbarBannerImg