How to concatenate strings from different columns and an additional string using a MySQL query?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
(
   FirstName varchar(100),
   LastName varchar(100)
);
Query OK, 0 rows affected (0.76 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Chris','Brown');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Adam','Smith');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Carol','Taylor');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('David','Miller');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| Chris     | Brown    |
| Adam      | Smith    |
| Carol     | Taylor   |
| David     | Miller   |
+-----------+----------+
4 rows in set (0.00 sec)

Following is the query to perform concatenation. Here, we have FirstName and LastName. With that an additional string is also concatenated in the beginning for all the string values −

mysql> select concat('Hello ',FirstName,' ',LastName) from DemoTable;

This will produce the following output −

+-----------------------------------------+
| concat('Hello ',FirstName,' ',LastName) |
+-----------------------------------------+
| Hello Chris Brown                       |
| Hello Adam Smith                        |
| Hello Carol Taylor                      |
| Hello David Miller                      |
+-----------------------------------------+
4 rows in set (0.00 sec)
raja
Published on 24-Sep-2019 13:40:30
Advertisements