Combine two MySQL fields and update a third one with result?



Following is the syntax to combine two fields in MySQL −

alter table yourTableName add column yourColumnName dataType;  update yourTableName set yourAddedColumnName =concat(yourColumnName1,' ',yourColumnName2);

Let us first create a table −

mysql> create table DemoTable1590    -> (    -> FirstName varchar(20),    -> LastName varchar(20)    -> ); Query OK, 0 rows affected (0.57 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1590 values('Adam','Smith'); Query OK, 1 row affected (0.45 sec) mysql> insert into DemoTable1590 values('John','Doe'); Query OK, 1 row affected (0.42 sec) mysql> insert into DemoTable1590 values('David','Miller'); Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1590;

This will produce the following output −

+-----------+----------+ | FirstName | LastName | +-----------+----------+ | Adam      |    Smith | | John      |      Doe | | David     |   Miller | +-----------+----------+ 3 rows in set (0.00 sec)

Following is the query to combine two MySQL fields and update third field after concatenation −

mysql> alter table DemoTable1590 add column FullName varchar(40); Query OK, 0 rows affected (0.54 sec) Records: 0  Duplicates: 0  Warnings: 0 mysql> update DemoTable1590 set FullName=concat(FirstName,' ',LastName); Query OK, 3 rows affected (0.56 sec) Rows matched: 3  Changed: 3 Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable1590;

This will produce the following output −

+-----------+----------+--------------+ | FirstName | LastName | FullName     | +-----------+----------+--------------+ | Adam      |    Smith | Adam Smith   | | John      |      Doe | John Doe     | | David     |   Miller | David Miller | +-----------+----------+--------------+ 3 rows in set (0.00 sec)
Updated on: 2019-12-16T06:49:03+05:30

535 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements