Please consider normalizing your data. Is storing a delimited list in a database column really that bad? The design you have here will make you crazy if your application actually grows.
In the meantime, you want to use column LIKE '%value%'
in place of column = 'value'
. Beware: the performance of this kind of query is very bad and can't be improved.
EDIT Queries using column = 'value'
or even column LIKE 'value%'
can exploit indexes in the database management system. It's possible to look up values in an index in O(log(n)) time. That permits even a vast table, with billions of rows, to be accessed efficiently. However, a query containing column LIKE '%value%'
has to scan through all the data, row by row, exhaustively looking for matches, in O(n) time. If you have a few hundred rows you won't notice this poor performance. But if your table grows you will definitely be sorry.
Try this query.
SELECT *
FROM table
WHERE column LIKE CONCAT('%' , 'Page2', '%')
LIMIT 1
I suggested the use of CONCAT()
so the query can easily be modified to use bind parameters. For example, CONCAT('%' ,? , '%')
Another edit. If you have Page1, Page100, Page101
you'll get a lot of false positive matches on Page1
. In MySQL FIND_IN_SET()
can do a search of a comma-separated string.
SELECT *
FROM table
WHERE FIND_IN_SET('Page2', column) <> 0
LIMIT 1
This will not work if you have spaces after your commas. Page1,Page2,Page3
is fine, but Page1, Page2, Page3
is no good. We can patch that problem like so.
SELECT *
FROM table
WHERE FIND_IN_SET('Page2', REPLACE(column, ', ', ',')) <> 0
LIMIT 1
But now things are getting out of hand. What if you have two spaces after a comma someplace? Or three?
This too is an unoptimizable search.