SQL Standard

SQL CURRENT_DATE

Accurate time and date are invaluable tools when it comes to databases. One of the most common tasks when dealing with databases and time is determining the current date.

SQL comes packed with lots of tools and functions for manipulating, retrieving, and using the date and time information including the current date and time.

In this tutorial, we will learn about the current date and all the functions that we can use to obtain it in SQL database.

SQL CURRENT_DATE Function

As the name suggests, the CURRENT_DATE() function in SQL allows us to retrieve the current date of the system in which the database server is running.

The function is very straightforward and does not support any argument. The following shows the basic syntax of the function:

SELECT CURRENT_DATE;

The function returns the current date in the default format that is specified in the database server.

Example 1: Basic Usage

Consider the following example statement that demonstrates how to use this function to get the current date on the target system:

SELECT CURRENT_DATE;

This should return an output as follows:

CURRENT_DATE|
------------+
2024-01-02|

Example 2: Filtering with CURRENT_DATE()

We can also use the CURRENT_DATE() function to filter out the results that match or do not match the specified condition.

For example, suppose we have a table named “orders” with a column named “order_date”. We can use the CURRENT_DATE() function to get the records that were ordered in the current date as follows:

SELECT order_id, customer_id, order_date

FROM orders

WHERE order_date = CURRENT_DATE;

This should retrieve the records from the “orders” table where the “order_date” matches the current date.

Example 3: Inserting the CURRENT_DATE()

We can also use the CURRENT_DATE() function to insert the data into a table to record the current date. Take for example the following query:

INSERT INTO audit_log (user_id, action, date)

VALUES (100, 'Logged In', CURRENT_DATE);

In this example, we use the CURRENT_DATE() function to get and insert the current date in the “date” column.

Conclusion

Through this post, you learned the usage and workings of the CURRENT_DATE() function in SQL to insert and filter out the results based on the current date without manually hardcoding it.

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