Search code examples
mysqldefaultdefault-value

How do I set "MONTHNAME()" function as column default in MySQL?


Actually I need current month name as lowercase string as default value in one of the table column; DB table may look like Like:

name : john
joined : january

When I try to use mysql function LOWER( MONTHNAME( NOW() ) ) as defailt value this gives me error. Btw I'm not interested in creating triggers.

any magic queries to do that?


Solution

  • From the MySQL documentation:

    With one exception, enclose expression default values within parentheses to distinguish them from literal constant default values.

    So, the following should work:

    CREATE TABLE yourTable (
        month_name VARCHAR(12) DEFAULT (LOWER(MONTHNAME(NOW())))
        ...
    )
    

    As @Madhur has pointed out, using an expression as a default will only work from MySQL 8 onwards.