SQL - How to check if item is in a list in a record

Evik James picture Evik James · Jun 15, 2011 · Viewed 12.7k times · Source

I have have a column name MyRoles that contains a list of items (integers) stored in a field named UserRoles. I want to write a query that checks to see if a specific item is in the list. The list will look like this: "1,2,3"

I can't use WHERE MyRoles

What should the query look like?

This is similar to what I am thinking:

SELECT *
FROM MyTable
WHERE MyRoles CONTAINS ('1')

The fact that no answer was easy to implement and would take me farther down an ugly road really makes clear that a normalized database is always the best bet.

Answer

Oded picture Oded · Jun 15, 2011

You can use LIKE:

SELECT *
FROM MyTable
WHERE MyRoles LIKE ('%1%')

This is likely to perform very badly (as an index will be fairly useless for such a search). And of course, will also match on 10 even if 1 doesn't exist in the query. You can extend the approach:

SELECT *
FROM MyTable
WHERE MyRoles = '1'
  OR MyRoles LIKE '1,%'
  OR MyRoles LIKE '%,1,%'

A better solution would be to normalize your database and not have multi-valued fields. Use a many-to-many table with single role ids and item ids per row. This is much easier to query.

Some databases will have better facilities for such a query, but these would be extensions and not standard SQL - you didn't mention a specific RDBMS.