Concat a string to SELECT * in MySQL?

MySQLMySQLi Database

To concat a string, use the CONCAT() function from MySQL as shown in the below syntax

SELECT
CONCAT(yourColumnName1,’anyConcatenationString’),CONCAT(yourColumnName2,’anyC
oncatenationString’),....N from yourTableName;

To understand the above syntax, let us first create a table. The query to create a table is as follows

mysql> create table selectConcat
-> (
-> StudentId int,
-> StudentName varchar(100),
-> StudentAge int
-> );
Query OK, 0 rows affected (1.32 sec)

Insert some records in the table using insert command. The query is as follows

mysql> insert into selectConcat values(1,'Carol',23);
Query OK, 1 row affected (0.19 sec)

mysql> insert into selectConcat values(2,'John',24);
Query OK, 1 row affected (0.25 sec)

mysql> insert into selectConcat values(3,'Adam',25);
Query OK, 1 row affected (0.14 sec)

mysql> insert into selectConcat values(4,'Bob',21);
Query OK, 1 row affected (0.20 sec)

mysql> insert into selectConcat values(5,'Sam',22);
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement. The query is as follows

mysql> select *from selectConcat;

The following is the output

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
| 1         | Carol       | 23         |
| 2         | John        | 24         |
| 3         | Adam        | 25         |
| 4         | Bob         | 21         |
| 5         | Sam         | 22         |
+-----------+-------------+------------+
5 rows in set (0.00 sec)

Contact the field in select statement. The query is as follows

mysql> select concat(StudentId,' as an Id'),concat(StudentName,' as a Name') from selectConcat;

The following is the output

+-------------------------------+----------------------------------+
| concat(StudentId,' as an Id') | concat(StudentName,' as a Name') |
+-------------------------------+----------------------------------+
| 1 as an Id                    | Carol as a Name                  |
| 2 as an Id                    | John as a Name                   |
| 3 as an Id                    | Adam as a Name                   |
| 4 as an Id                    | Bob as a Name                    |
| 5 as an Id                    | Sam as a Name                    |
+-------------------------------+----------------------------------+
5 rows in set (0.00 sec)
raja
Published on 11-Jan-2019 09:56:31
Advertisements