PostgreSQL offers a wide range of data and time functions such as CURRENT_DATE, TO_DATE(), NOW(), CURRENT_TIME, and so on. Among them, the most widely used function is the CURRENT_DATE function which retrieves today’s date.
So, the CURRENT_DATE function will be the topic of discussion in this blog post, where we will examine various use cases of the targeted function.
How Does the CURRENT_DATE Function Work in Postgres?
In PostgreSQL, the CURRENT_DATE function doesn’t take any argument, as shown in the below-stated syntax:
CURRENT_DATE;
Unlike any other traditional function, it doesn't require any parenthesis. It retrieves a DATE value representing today’s date.
The best way to comprehend a concept is to implement it practically! So, let’s do it!
Example 1: Basic Usage of the CURRENT_DATE Function
The following snippet will show you the basic usage of the CURRENT_DATE function in Postgres:
SELECT CURRENT_DATE;
The output snippet shows that the stated function retrieves today’s date.
Example 2: Use the CURRENT_DATE Function as a Default Value of a Table’s Column
Firstly, we will create a new sample table, let’s say “submit_articles”. The table consists of three columns article_id, article_title, and submission_date. Suppose we want to set the CURRENT_DATE as the default submission date. To do so, we will set the CURRENT_DATE function as a default value of the submission_date column:
CREATE TABLE submit_articles( article_id INTEGER PRIMARY KEY, article_title TEXT, submission_date DATE DEFAULT CURRENT_DATE);
The submit_articles table has been created. Let’s validate the table’s creation via the below command:
SELECT * FROM submit_articles;
Let’s insert some records into the submit_articles table via the INSERT INTO statement:
INSERT INTO submit_articles(article_id, article_title) VALUES(1, 'Postgres DROP CASCADE'), (2, 'Postgres DROP TABLE'), (3, 'Postgres CREATE TABLE'), (4, 'Postgres DROP DATABASE'), (5, 'Postgres CREATE DATABASE');
Five records have been inserted into the submit_articles table. From the above snippet, you can clearly observe that we didn’t insert any value in the submission_date column. Let’s execute the SELECT statement one more time and see what the output says:
SELECT * FROM submit_articles;
The output depicts that Postgres specifies the current date as a default value in the submission_date column. This way, you can specify the current/today’s date as a default value in any particular column using the CURRENT_DATE function.
That’s all from this Postgres guide!
Conclusion
CURRENT_DATE is one of the Postgres built-in date functions that retrieve the current/today’s date. It doesn’t take any argument. You can set the current date as a default value of any table’s columns using the CURRENT_DATE function. Through practical examples, this blog post demonstrated how to get today’s date using the CURRENT_DATE function.