How the CURDATE() function works in Mariadb?

The CURDATE() function is a date and time function that returns the current date as a value in YYYY-MM-DD format.

Posted on

The MariaDB CURDATE() function is used to retrieve the current date in YYYY-MM-DD format, which is particularly useful for recording timestamps in data entries and comparing dates within database queries.

Syntax

The syntax for the MariaDB CURDATE() function is as follows:

CURDATE()

This function does not take any arguments and returns the current date as a value in YYYY-MM-DD format.

Examples

Retrieve the Current Date

To simply get the current date, you would use the CURDATE() function like this:

SELECT CURDATE();

The output will be the current date:

+------------+
| CURDATE()  |
+------------+
| 2024-02-14 |
+------------+

Compare Dates

If you want to compare the current date with a specific date to find out if it is the same, you can do so using the CURDATE() function:

SELECT CURDATE() = '2024-02-14' AS Is_Today;

The output will indicate whether the current date is the specified date:

+----------+
| Is_Today |
+----------+
|        1 |
+----------+

Calculate Age

To calculate the age from a birthdate, you can use the CURDATE() function in a date subtraction:

SELECT YEAR(CURDATE()) - YEAR('1990-05-25') AS Age;

This will return the age:

+------+
| Age  |
+------+
|   34 |
+------+

Check for a Specific Month

You can check if the current month is, for example, March:

SELECT MONTH(CURDATE()) = 3 AS Is_March;

The output will show whether it’s March or not:

+----------+
| Is_March |
+----------+
|        1 |
+----------+

Using CURDATE() with WHERE Clause

If you need to filter records based on the current date, you can use CURDATE() in the WHERE clause:

DROP TABLE IF EXISTS orders;
CREATE TABLE orders (
    order_id INT,
    order_date DATE
);
INSERT INTO orders VALUES (1, '2024-02-14'), (2, '2024-03-16');

SELECT * FROM orders WHERE order_date = CURDATE();

The output will display rows with today’s date:

+----------+------------+
| order_id | order_date |
+----------+------------+
|        1 | 2024-02-14 |
+----------+------------+

Here are a few functions related to the MariaDB CURDATE() function:

  • MariaDB NOW() function is used to retrieve the current date and time.
  • MariaDB DATE() function is used to extract the date part from a datetime expression.
  • MariaDB DAYOFMONTH() function returns the day of the month from a date.
  • MariaDB MONTH() function extracts the month from the date.
  • MariaDB YEAR() function returns the year from a date.

Conclusion

Understanding the CURDATE() function in MariaDB is essential for working with date values within your databases. It allows for easy retrieval and comparison of dates, which can be used in a variety of applications such as reporting, data analysis, and more. By combining CURDATE() with other date and time functions, you can perform complex queries and data manipulations with ease.