Click here to Skip to main content
15,880,392 members
Articles / Programming Languages / SQL
Tip/Trick

How to Query Comma Separated Value Column in SQL

Rate me:
Please Sign up or sign in to vote.
4.98/5 (25 votes)
28 May 2016CPOL2 min read 89.8K   15   23
How to query comma separated value column in SQL

Introduction

This is a small SQL function which will be useful for querying a Table which is having a comma separated value column.

Background

Sometimes, you encounter a column that stores comma separated values. This solution makes it easy to search such a column. However, it is recommended, if possible, to split the tables into two according to the First Normal Form.

For example: Storing the days of week in CSV format [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Sunday], for months in numbers [1,2,3,4,5,6,7,8,9,10,11,12]

I came across this requirement for storing the days in CSV format as reminder follow up for the user, and to query it.

Problem

Sometimes, we used to store a comma separated value in a column and which we will be using for some purpose in order to avoid creating a new table for that functionality. In this case, equals = search or contains Search or Like query will not work as expected to find one or more item present in the comma separated value Column, Inorder to overcome the problem I have created this function for querying the column in multiple scenarios which the developer can use according to his/her need.

Using the Code

First, we have to create a User Defined Function, which will take the comma separated value as the input and returns the items in a table format.

SQL
 create function dbo.fun_CSVtoTable(
 @csv nvarchar (4000),
 @Delimiter nvarchar (10)
 )
returns @returnValue table ([Item] nvarchar(4000))
begin
 declare @NextValue nvarchar(4000)
 declare @Position int
 declare @NextPosition int
 declare @comma nvarchar(1) 
 set @NextValue = ''
 set @comma = right(@csv,1)  
 set @csv = @csv + @Delimiter 
 set @Position = charindex(@Delimiter,@csv)
 set @NextPosition = 1 
 while (@Position <>  0)  
 begin
  set @NextValue = substring(@csv,1,@Position - 1) 
  insert into @returnValue ( [Item]) Values (@NextValue) 
  set @csv = substring(@csv,@Position +1,len(@csv))  
  set @NextPosition = @Position
  set @Position  = charindex(@Delimiter,@csv)
 end 
 return
end

The below User Defined Function is used for querying the items in CSV column under different scenarios such as Contains Search, Exact Match Search, Exact Contains Search.

SQL
create function dbo.fun_QueryCSVColumn(
 @csvColumn nvarchar (4000),
 @Delimiter nvarchar (2),
 @value nvarchar(4000),
 @search nvarchar(50) -- 'contains' | 'exact contains' | 'exact match'
 )
returns   nvarchar(1)
begin
declare @return varchar(1) = '0'
declare @table_ColumnValue table (value nvarchar(100))
declare @table_InputValue table (value nvarchar(100))
declare @joinCount int
declare @valuecount int
declare @Columnvaluecount int
insert into @table_ColumnValue  select distinct item from dbo.fun_CSVtoTable(@csvColumn,@Delimiter)
insert into @table_InputValue  select distinct item  from dbo.fun_CSVtoTable(@value,@Delimiter)
 select @joinCount =  count(*) from @table_ColumnValue a inner join _
     @table_InputValue b on a.value = b.value
 select @valuecount = count(*) from @table_InputValue
 select @Columnvaluecount = count(*) from @table_ColumnValue
 if(@search = 'contains') begin
 if @joinCount >0
 set @return = '1'  
 end
 else if (@search = 'exact contains')
 begin   
 if(@joinCount = @valuecount)
 set @return = '1' 
 end
else if (@search = 'exact match')
begin
 if( @joinCount = @valuecount and @joinCount= @Columnvaluecount )
 set @return ='1'
end 
 return @return
 
end

After the above function is created, we can use the below queries to Search the item(s) in the CSV column.

I have used the below table for demo purposes.

CSVColumn
a,b
a,b,c
a
b
c
a,c
Querying the above column in 3 different scenarios:

Contains

SQL
select * from mytable where '1' = dbo.fun_QueryCSVColumn (CSVColumn,',','a','contains')
CSVColumn
a,b
a,b,c
a
a,c
SQL
select * from mytable where '1' = dbo.fun_QueryCSVColumn (CSVColumn,',','b,a','contains')
CSVColumn
a,b
a,b,c
a
b
a,c

Exact Contains

SQL
select * from mytable where '1' = dbo.fun_QueryCSVColumn (CSVColumn,',','b,a','exact contains')
CSVColumn
a,b
a,b,c
SQL
select * from mytable where '1' = dbo.fun_QueryCSVColumn (CSVColumn,',','c,b','exact contains')
CSVColumn
a,b,c

Exact Match

SQL
select * from mytable where '1' = dbo.fun_QueryCSVColumn (CSVColumn,',','a,b,c','exact match') 
CSVColumn
a,b,c
SQL
select * from mytable where '1' = dbo.fun_QueryCSVColumn (CSVColumn,',','b,a','exact match')
CSVColumn
a,b

Points of Interest

But one thing you should keep in mind is, this will reduce the performance of the select query since we are using User defined function in select statement, we should use this only when the CSV items are very few and the rows length is considerable range.

Before creating a CSV column, just read about Database Normalisation.

I have used Comma in the example, you shall use any char as delimiter, it depends upon how you are storing the values in the table.

History

  • Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Infosys
India India
All is well Smile | :)

Comments and Discussions

 
PraiseA nice and informative article Pin
Eyssan5-May-20 6:49
professionalEyssan5-May-20 6:49 
Questionwhat is class Pin
Member 1416106031-May-19 19:32
Member 1416106031-May-19 19:32 
SuggestionInstead of string comparision you can use int for faster response. Pin
Sunasara Imdadhusen9-May-18 2:42
professionalSunasara Imdadhusen9-May-18 2:42 
QuestionGood Going Karthik Pin
Member 1356904310-Dec-17 20:24
professionalMember 1356904310-Dec-17 20:24 
AnswerRe: Good Going Karthik Pin
Karthik_Mahalingam10-Dec-17 22:05
professionalKarthik_Mahalingam10-Dec-17 22:05 
QuestionThanks Pin
Member 1241126722-Feb-17 22:12
Member 1241126722-Feb-17 22:12 
AnswerRe: Thanks Pin
Karthik_Mahalingam22-Feb-17 23:17
professionalKarthik_Mahalingam22-Feb-17 23:17 
GeneralMy vote of 5 Pin
Maciej Los28-Aug-16 10:04
mveMaciej Los28-Aug-16 10:04 
GeneralRe: My vote of 5 Pin
Karthik_Mahalingam28-Aug-16 18:17
professionalKarthik_Mahalingam28-Aug-16 18:17 
QuestionPerformance? Pin
Member 125684306-Jun-16 6:30
Member 125684306-Jun-16 6:30 
PraiseKeep it up! Pin
Peter Leow28-May-16 2:11
professionalPeter Leow28-May-16 2:11 
GeneralRe: Keep it up! Pin
Karthik_Mahalingam28-May-16 2:29
professionalKarthik_Mahalingam28-May-16 2:29 
Praise5 Stars!!! ***** Pin
Santosh Kokatnur25-May-16 4:32
Santosh Kokatnur25-May-16 4:32 
GeneralRe: 5 Stars!!! ***** Pin
Karthik_Mahalingam25-May-16 4:40
professionalKarthik_Mahalingam25-May-16 4:40 
GeneralMy vote of 5 Pin
arroway23-May-16 20:27
arroway23-May-16 20:27 
GeneralRe: My vote of 5 Pin
Karthik_Mahalingam23-May-16 20:30
professionalKarthik_Mahalingam23-May-16 20:30 
QuestionInteresting article. One suggestion... Pin
Emily Heiner23-May-16 7:05
Emily Heiner23-May-16 7:05 
AnswerRe: Interesting article. One suggestion... Pin
Karthik_Mahalingam23-May-16 7:11
professionalKarthik_Mahalingam23-May-16 7:11 
QuestionWhen should you ever store comma separated values in a column? Pin
George Jonsson21-May-16 17:24
professionalGeorge Jonsson21-May-16 17:24 
AnswerRe: When should you ever store comma separated values in a column? Pin
Karthik_Mahalingam21-May-16 18:07
professionalKarthik_Mahalingam21-May-16 18:07 
SuggestionRe: When should you ever store comma separated values in a column? Pin
George Jonsson21-May-16 18:55
professionalGeorge Jonsson21-May-16 18:55 
GeneralRe: When should you ever store comma separated values in a column? Pin
Karthik_Mahalingam21-May-16 19:09
professionalKarthik_Mahalingam21-May-16 19:09 
GeneralRe: When should you ever store comma separated values in a column? Pin
George Jonsson21-May-16 19:36
professionalGeorge Jonsson21-May-16 19:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.