Tags
MySQL
Asked 5 years ago
2 Oct 2018
Views 683
steave ray

steave ray posted

mysql only store month year field type

i am making the report and save it to database table name report
but report based on the monthly . not date wise . but question is which field type suitable for month-year only

we have date / datetime filed type in mysql but not specific any field type for month-year
steave

steave
answered Apr 25 '23 00:00

MySQL does not have a specific data type to store only a month and year. However, you can use the DATE data type to store a date and use a fixed value for the day to represent only the month and year. For example, you can set the day to 01 to represent the first day of the month. Here's an example of how to create a table with a column that stores only the month and year:


CREATE TABLE my_table (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  month_year DATE NOT NULL
);

To insert a value that represents only the month and year, you can use the STR_TO_DATE function to convert a string to a date format with the day set to 01. Here's an example:




INSERT INTO my_table (month_year) VALUES (STR_TO_DATE('2022-04', '%Y-%m'));

In this example, we're using the STR_TO_DATE function to convert the string '2022-04' to a DATE value with the format %Y-%m , which represents a year and month with a dash separator (e.g., 2022-04). The resulting DATE value will have a day of 01 and the month and year of the input string.

To retrieve only the month and year from the month_year column, you can use the DATE_FORMAT function with the %Y-%m format specifier:


SELECT DATE_FORMAT(month_year, '%Y-%m') AS month_year FROM my_table;

This will return a result set with a single column named month_year containing values like 2022-04, which represent only the month and year of the original DATE value.
Post Answer