SQL Concat
SQL Concat is used to combine the record set of different fields.
Understand with Example
The Tutorial helps you to understand the example from 'SQL Concat'. To understand and grasp the example we create a table 'Stu' that has the required fieldnames and datatypes respectively.
Create Table Stu:
create table Stu(Id varchar(2), Name varchar(15), Class varchar(10),sub_id varchar(2),marks varchar(3)); |
Insert data into Stu:
The insert into adds the records value to the table 'Stu'.
insert into Stu values(1,'Komal',10,1,45); insert into Stu values(2,'Ajay',10,1,56); insert into Stu values(3,'Rakesh',10,1,67); insert into Stu values(4,'Santosh',10,1,67); insert into Stu values(1,'Komal',10,2,47); insert into Stu values(2,'Ajay',10,2,53); insert into Stu values(3,'Rakesh',10,2,57); insert into Stu values(4,'Santosh',10,2,67); insert into Stu values(5,'Bhanu',10,2,67); insert into Stu values(1,'Komal',10,3,45); insert into Stu values(2,'Ajay',10,3,56); insert into Stu values(3,'Rakesh',10,3,67); insert into Stu values(4,'Santosh',10,3,67); insert into Stu values(5,'Bhanu',10,3,67); insert into Stu values(1,'Komal',10,4,65); insert into Stu values(2,'Ajay',10,4,56); insert into Stu values(3,'Rakesh',10,4,37); insert into Stu values(4,'Santosh',10,4,67); insert into Stu values(5,'Bhanu',10,2,67); insert into Stu values(1,'Komal',10,5,65); insert into Stu values(2,'Ajay',10,5,46); insert into Stu values(3,'Rakesh',10,5,63); |
Concatenate Functions:
The Query below is used to combine the records of different marks value and sort the records on the basis of id fro table 'stu'.
mysql> select id, name, GROUP_CONCAT(marks order by sub_id) -> from stu group by id; +------+---------+-------------------------------------+ | id | name | GROUP_CONCAT(marks order by sub_id) | +------+---------+-------------------------------------+ | 1 | Komal | 45,47,45,65,65 | | 2 | Ajay | 56,53,56,56,46 | | 3 | Rakesh | 67,57,67,37,63 | | 4 | Santosh | 67,67,67,67 | | 5 | Bhanu | 67,67,67 | +------+---------+-------------------------------------+ 5 rows in set (0.00 sec) |