Microsoft SQL Server Filter rows by array values


If you store a list of tags in a row as coma separated values, STRING_SPLIT function enables you to transform list of tags into a table of values. CROSS APPLY enables you to "join" values parsed by STRING_SPLIT function with a parent row.

Imagine that you have a Product table with a column that contains an array of comma separated tags (e.g. promo,sales,new). STRING_SPLIT and CROSS APPLY enable you to join product rows with their tags so you can filter products by tags:

FROM Products p 
     CROSS APPLY STRING_SPLIT( p.Tags, ',' ) tags
WHERE tags.value = 'promo'

For each row, value of Tags cell will be provided to STRING_SPLIT function that will return tag values. Then you can filter rows by these values.

Note: STRING_SPLIT function is not available before SQL Server 2016