How to concatenate all columns in MySQL?



First, you need to know how many columns are present in a table. Following is the syntax to know the column names −

show columns from yourTableName;

Following is the syntax to concatenate all columns −

select concat(yourColumnName1,yourColumnName2,yourColumnName3,........N) from yourTableName;

Let us first create a table −

mysql> create table DemoTable    (    CustomerId int,    CustomerName varchar(20),    CustomerAge int    ); Query OK, 0 rows affected (0.66 sec)

Following is the query to know the exact column −

mysql> show columns from DemoTable;

This will produce the following output −

+--------------+-------------+------+-----+---------+-------+ | Field        | Type        | Null | Key | Default | Extra | +--------------+-------------+------+-----+---------+-------+ | CustomerId   | int(11)     | YES  |     | NULL    |       | | CustomerName | varchar(20) | YES  |     | NULL    |       | | CustomerAge  | int(11)     | YES  |     | NULL    |       | +--------------+-------------+------+-----+---------+-------+ 3 rows in set (0.00 sec)

Insert records in the table using insert command −

mysql> insert into DemoTable values(101,'Chris',26); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(102,'Robert',27); Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+------------+--------------+-------------+ | CustomerId | CustomerName | CustomerAge | +------------+--------------+-------------+ | 101        | Chris        | 26          | | 102        | Robert       | 27          | +------------+--------------+-------------+ 2 rows in set (0.00 sec)

Following is the query to concat all columns −

mysql> select concat(CustomerId,CustomerName,CustomerAge) from DemoTable;

This will produce the following output −

+---------------------------------------------+ | concat(CustomerId,CustomerName,CustomerAge) | +---------------------------------------------+ | 101Chris26 | | 102Robert27 | +---------------------------------------------+ 2 rows in set (0.00 sec)
Updated on: 2019-07-30T22:30:26+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements