Sunday, December 22, 2024

MySQL DAY() Function

 The MySQL DAY() function is used to extract the day of the month (a number from 1 to 31) from a given date.

Syntax:

DAY(date)

Parameters:

  • date: A valid date, datetime, or a string in a valid date format.

Returns:

  • An integer value representing the day of the month.

Examples:

  1. Extract the day from a date:

    SELECT DAY('2024-12-23') AS DayOfMonth;
    

    Output:

    DayOfMonth
    23
    
  2. Using with a datetime value:

    SELECT DAY('2024-12-23 15:30:00') AS DayOfMonth;
    

    Output:

    DayOfMonth
    23
    
  3. Using a column from a table:

    SELECT order_id, DAY(order_date) AS DayOfMonth
    FROM orders;
    
  4. Invalid date input: If the date provided is invalid, DAY() will return NULL.

    SELECT DAY('invalid-date') AS DayOfMonth;
    

    Output:

    DayOfMonth
    NULL
    

Notes:

  • It is often used in conjunction with other date and time functions in MySQL.
  • The function is case-insensitive, so day() works the same as DAY().

If you need to extract a specific part of the date, such as the year or month, you can use related functions like YEAR(), MONTH(), etc.

No comments:

Post a Comment