Search code examples
mysqlsqlconcatenation

Automatically concatenate a value in a coulmn in SQL


Im looking for a way to create a column that is automatically filled with a concatenated value of two inserted values.

Lets say I have a table with first name, last name and full name columns.

When i insert values, i will just insert the first name and last name values where the full name column will have the value of these two concatenated automatically.

My project is to create a work order request number based on machine name and request timestamp.

Is such thing possible ?

Thanks


Solution

  • You want a generated column, available in MySQL 5.7 and later.

    For example:

    create table demo (
    firstName varchar(40),
    lastname varchar(40),
    fullName varchar(60) as (concat(firstName,' ', lastName))
    );
    
    insert demo (firstName,lastName) values ('John', 'Doe'),('Jane','Doe'),('Fred','Smith');
    
    select * from demo;
    

    Output:

    firstName   lastname    fullName
    John        Doe         John Doe
    Jane        Doe         Jane Doe
    Fred        Smith       Fred Smith