Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if record exists in database - fastest method

I have a table where I store unique text strings and then I check if that string exists in the database by doing select

String checkIfAlreadyScanned = "SELECT id FROM \"STRINGS_DB\"  where STR ='" + mystring + "'";

then I check if value exists. My database has around 5mil records; can I improve my method?

Maybe there is a way of creating a new attribute (hashedSTR) for example and convert string into some unique numberical value and then getting these numbers, instead of strings? Will that work faster? (will that work at all?)

like image 328
Andrew Avatar asked Dec 27 '22 21:12

Andrew


1 Answers

To ensure the fastest processing, make sure:

  • The field you are searching on is indexed (you told about an "unique" string, so I suppose it is already the case. For this reason, "limit 1" is not necessary. Otherwise, it should be added)
  • You are using the ExecuteScalar() method of your Command object
like image 173
Larry Avatar answered Dec 29 '22 10:12

Larry