Search code examples
phpmysqldatabasedefaultdefault-value

MySQL - set dynamic default value


I have table of users in my MySQL database. Is it possible to set default value of column profile_url to value of column Id ?


Solution

  • You could use trigger to implement the feature. For example:

    CREATE TRIGGER defaultUrl
    BEFORE INSERT ON MyTable
    FOR EACH ROW 
    SET NEW.profile_url = IFNULL(NEW.profile_url, NEW.id);
    

    The expression creates a trigger named defaultUrl that activates before each row inserted into MyTable. If defaultUrl is NULL, the id value is used.