Search code examples
sqlmysqlfunctiondefault-value

MySQL - Set default value for field as a string concatenation function


I have a table that looks a bit like this actors(forename, surname, stage_name);

I want to update stage_name to have a default value of

forename." ".surname

So that

insert into actors(forename, surname) values ('Stack', 'Overflow');

would produce the record

'Stack'     'Overflow'    'Stack Overflow'

Is this possible?

Thanks :)


Solution

  • MySQL does not support computed columns or expressions in the DEFAULT option of a column definition.

    You can do this in a trigger (MySQL 5.0 or greater required):

    CREATE TRIGGER format_stage_name 
    BEFORE INSERT ON actors
    FOR EACH ROW
    BEGIN
      SET NEW.stage_name = CONCAT(NEW.forename, ' ', NEW.surname);
    END
    

    You may also want to create a similar trigger BEFORE UPDATE.

    Watch out for NULL in forename and surname, because concat of a NULL with any other string produces a NULL. Use COALESCE() on each column or on the concatenated string as appropriate.

    edit: The following example sets stage_name only if it's NULL. Otherwise you can specify the stage_name in your INSERT statement, and it'll be preserved.

    CREATE TRIGGER format_stage_name 
    BEFORE INSERT ON actors
    FOR EACH ROW
    BEGIN
      IF (NEW.stage_name IS NULL) THEN
        SET NEW.stage_name = CONCAT(NEW.forename, ' ', NEW.surname);
      END IF;
    END