SQLite Tutorial SQLite Advanced SQLite Database SQLite References

SQLite GROUP_CONCAT() Function



The SQLite GROUP_CONCAT() function returns a string which is the concatenation of all non-NULL values of an expression where the value of expression is not NULL. If second argument is provided then it is used as the separator between the values. If the second argument is omitted, a comma , is used as the separator. The order of the concatenated elements is arbitrary.

GROUP_CONCAT(X) 
GROUP_CONCAT(X, Y) 

Syntax

The syntax for using GROUP_CONCAT() function is given below:

SELECT GROUP_CONCAT(column_name) 
FROM table_name
WHERE condition(s);

The SQLite GROUP BY clause is used to arrange result table into identical groups when one or more columns are used. Please note that it is must to include those column names in a GROUP BY clause which are not encapsulated within the GROUP_CONCAT() function. See the syntax below:

SELECT column1, column2, ...
       GROUP_CONCAT(column_name) 
FROM table_name
WHERE condition(s)
GROUP BY column1, column2, ...;

Parameters

column1, column2, ... Specify the column names that are not encapsulated within the GROUP_CONCAT() function. It must be included in the GROUP BY clause.
column_name Specify the column or expression whose non-null values need to be counted.
table_name Specify the table name from where the records need to retrieved.
WHERE condition(s) Optional. Specify the condition(s). Records are selected based upon specified condition(s).

Return Value

Returns a string which is the concatenation of all non-NULL values of a given expression.

Example - With Single Column

Consider a database table called Employee with the following records:

EmpIDNameCityAgeSalary
1JohnLondon253000
2MarryNew York242750
3JoParis272800
4KimAmsterdam303100
5RameshNew Delhi283000
6HuangBeijing282800

To get the string containing names of the employee whose age is greater than 25, the following query can be used:

SELECT GROUP_CONCAT(Name) AS EmployeeGT25 
FROM Employee
WHERE Age > 25;

This will produce the result as shown below:

EmployeeGT25
Jo,Kim,Ramesh,Huang


Example - Using DISTINCT

The DISTICT clause can be used with GROUP_CONCAT() function. For example - To get the string containing distinct (unique) ages of the employee, the following statement can be used:

SELECT GROUP_CONCAT(DISTINCT Age) AS DistinctAge 
FROM Employee;

This will produce the result as shown below:

DistinctAge
25,24,27,30,28


Example - Using GROUP BY

To get the names of the employees group by their age, the following query can be used:

SELECT Age, GROUP_CONCAT(Name) AS EmployeeNames 
FROM Employee
GROUP BY Age;

This result of the above code will be:

AgeEmployeeNames
24Marry
25John
27Jo
28Ramesh,Huang
30Kim

❮ SQLite Functions