Does anyone know what the complexity is for the SQL LIKE
operator for the most popular databases?
views:
249answers:
3Depends on the RDBMS, the data (and possibly size of data), indexes and how the LIKE is used (with or without prefix wildcard)!
You are asking too general a question.
If you are asking about the performance impact:
The problem of like is that it keeps the database from using an index. On Oracle I think it doesn't use indexes anymore (but I'm still on Oracle 9). SqlServer uses indexes if the wildcard is only at the end. I don't know about other databases.
For MySQL:
LIKE 'foo%' is quite fast if run on an indexed column. Descending the B-tree to the correct position is a very fast operation. After that it depends on how long the range is.
LIKE '%foo%' has O(n) complexity. If it's your only criteria that means a full table scan. If you have other criterias that can by executed using indices, it will only scan the the rows that remain after the initial filtering.
A hack that sometime is used to speed things up is to store the column in reverse as well:
col LIKE 'foo%' OR col_reverse LIKE 'oof%'
This approach combined with smart usage of clustered indices can cause a major speedup. This only works for short fields, though, since MySQL has a maximum index length of 1024 bytes (if I remember correctly).