Using LIKE on Integers Gets You Implicit Conversion
5 Comments
Using the Stack Overflow public export, take these two queries looking for a particular user by Id (the clustering key):
|
1 2 |
SELECT * FROM dbo.Users WHERE Id = 26837; SELECT * FROM dbo.Users WHERE Id LIKE 26837; |
The first one (=) gets a clustered index seek, does just 3 logical reads, and correctly estimates that only 1 row will be returned.
The second one (LIKE) does a clustered index scan, reads the entire table, and wildly overestimates that 475,005 rows will be returned – even though only 1 row will.

The actual execution plans complete with the warning on the SELECT statement tell the story: SQL Server thinks you’re implicitly converting the Id to a VARCHAR(12), and then doing a comparison there.
Wanna go faster without changing your code? Sure, we all do – so give SQL Server a pre-converted field that it can use for comparisons:
|
1 2 |
ALTER TABLE dbo.Users ADD IdAsVarchar AS CAST(Id AS VARCHAR(12)); CREATE INDEX IX_IdAsVarchar ON dbo.Users(IdAsVarchar); |
We’re adding a computed field, then indexing that field.
Then run your really, really stupid query again – don’t change it, just run it exactly as-is:
|
1 |
SELECT * FROM dbo.Users WHERE Id LIKE 26837; |
And presto, SQL Server does an index seek on our newly created computed field:

Sure, it’s still warning about implicit conversion, but get this: it now correctly estimates just 1 row will come back, and does just 6 logical reads.
I’d rather fix the code, but if you can’t, this is a pretty spiffy way to help SQL Server do bad things – faster.















































