Given a string column with a value similar to /123/12/34/56/5/, what is the optimal way of querying for all the records that include the given number (12 for example)?
The solution from top of my head is:
SELECT id FROM things WHERE things.path LIKE '%/12/%'
But AFAIK this query can’t use indexes on the column due to the leading %.
There must be something better. What is it?
Using PostgreSQL, but would prefer the solution that would work across other DBs too.
In PostgreSQL 9.1 you could utilize the
pg_trgmmodule and build a GIN index with it.Your
LIKEexpression can use this index even if it is not left-anchored.See a detailed demo by depesz here.
Normalize it If you can, though.