MySQL CURDATE Function

MySQL CURDATE Function

MySQL CURDATE Function

The CURDATE() function in MySQL is used to return the current date. It does not return the time component, only the date in YYYY-MM-DD format.

Syntax

CURDATE()
  • The function takes no arguments and simply returns the current date from the system's clock.

Usage

The CURDATE() function is often used in queries that require the current date to perform calculations, comparisons, or filtering.

Examples

1. Get Current Date

Return today's date:

SELECT CURDATE() AS current_date;

Output:

current_date -------------- 2025-01-24

2. Using with WHERE Clause

Find all records where the date matches today's date:

SELECT * FROM orders WHERE order_date = CURDATE();

3. Using in Date Calculations

Use CURDATE() in date arithmetic (e.g., to find records from the past 7 days):

SELECT * FROM orders WHERE order_date >= CURDATE() - INTERVAL 7 DAY;

4. Combining with DATE_ADD() or DATE_SUB()

Get the date for 30 days ago:

SELECT DATE_SUB(CURDATE(), INTERVAL 30 DAY) AS thirty_days_ago;

5. Use in INSERT Statement

Insert the current date into a table:

INSERT INTO events (event_name, event_date) VALUES ('New Year Party', CURDATE());

Key Considerations

  1. No Time Component:

    • Unlike the NOW() function, which includes the time, CURDATE() only returns the date without any time information.
  2. Return Type:

    • The result of CURDATE() is always of type DATE, which is formatted as YYYY-MM-DD.
  3. Time Zone:

    • The current date returned by CURDATE() is based on the server's local time zone. To ensure consistency across different environments, consider adjusting the time zone if needed.

Common Use Cases

  1. Current Date in Reports: Display the current date in reports or dashboards.
  2. Filtering Records: Use in WHERE clauses to filter records based on today's date.
  3. Date Comparisons: Perform date-based comparisons for time-sensitive queries or calculations (e.g., overdue invoices).
  4. Tracking Creation/Modification Dates: Insert or update records with the current date in audit tables.

Conclusion

The CURDATE() function is a simple but essential tool in MySQL for retrieving the current date. Whether used for filtering, inserting data, or performing date calculations, it is integral in scenarios where the current date is needed without the time component. It is often paired with other date functions like DATE_ADD(), DATE_SUB(), and INTERVAL to perform more complex date-based queries.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close