Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is faster comparing an uniqueidentifier or a string in tsql?

I have a table which holds the guid for an user and their actual name as a string. I would like to grab some information based on an user. But which field should I use? Should my code say:

select * 
from userinboxcount 
where countDate >= startDate and countDate <= endDate and userid = '<guid here>'

or 

select * 
from userinboxcount 
where countDate >= startDate and countDate <= endDate and username = "FirstName LastName"
like image 227
dotnetN00b Avatar asked Jan 17 '23 16:01

dotnetN00b


2 Answers

The biggest difference is if one field has an index that the database can use, and the other doesn't. If the database has to read all the data in the table to scan for the value, the disk access takes so much resources that the difference in data type is not relevant.

If both fields have indexes, then the index that is smaller would be somewhat faster, because it loads faster, and it's more likely that it remains in the cache.

Ideally you would have an index for all the fields in the condition, which has the fields that you want to return as included fields. That way the query can produce the result from only the index, and doesn't have to read from the actual table at all. You should of course not use select *, but specify the fields that you actually need to return.

Other than that, it would be somewhat faster to compare GUID values because it's a simple numeric comparison and doesn't have to consider lexical rules.

like image 137
Guffa Avatar answered Jan 27 '23 05:01

Guffa


See the query plan and you can see it for yourself.

But the unique identifier usually has an index and the string (username) might not have. If so, and if there are many records, prolly the unique identifier would be faster!


To the the query plan, check THIS article.

like image 27
aF. Avatar answered Jan 27 '23 05:01

aF.