'SQL Date extraction month and year

The date format is 2018-02-04 , i would like to select the month and year from this to preferably get February, 2018, ill take 2018-02

the format is date/timestamp in postreg



Solution 1:[1]

  • If you're using MySQL, you can use DATE_FORMAT to format date as specified:

    SELECT DATE_FORMAT(date, '%Y-%m') FROM Table
    

    Check the documentation to find out more.

  • Otherwise, assuming the date format is YYYY-MM-DD, what you can do is simply CAST date column to a string format and use LEFT() function to extract only the year and the month:

    SELECT LEFT(CAST(date as varchar), 7) from Table
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1