I was given a test for a new job, and I can’t decide on which way to go, the question is as follows:
on a given database table (which I designed for another question):
message_id | INT PRIMARY AUTO_INCREMENT
user_id | INT FOREIGN_KEY
from_id | INT FOREIGN_KEY
message | TEXT
let’s say I want to search for a text in all the messages of a given user, would it be faster to do:
$query = "SELECT * FROM messages m WHERE user_id='$id' AND message LIKE '%$string%';
or would it be faster to do:
$query = "SELECT * FROM messages m WHERE user_id='$id';
and run on the result set I get, a substr_count()?
Or is there some faster, more efficent method to do this?
You should always search on database side. Although a
LIKE '%word%'causes always a full table scan, not every row has to get serialized, transferred to the client and deserialized again.Also, if you can optimize the query to use a fulltext index or to match only the last part of a word (e.g.
LIKE 'word%') a full table scan wouldn’t be necessary because it can be evaluated over an index (if it exists).