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:
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:
This should return an output as follows:
------------+
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:
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:
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.