Husam Zidan
Husam Zidan

Reputation: 629

Ms Sql Server Compare Numeric column with string value

In MS SQL Server, what is the difference between:

select * from Person where Id='7'

and

select * from Person where Id=7

The two queries returns the same results.

The Id type is int.

should we not compare int to string?

and when should use one of them?

Upvotes: 5

Views: 2329

Answers (1)

EzLo
EzLo

Reputation: 14209

Always compare with the same data type and avoid implicit conversions.

SELECT 'Not OK!' WHERE 'text' = 1
-- Result: Conversion failed when converting the varchar value 'text' to data type int.

As stated by the data type precedence, when there is a mismatch of the data types, the SQL engine will (in most cases) try to convert the most complex type to the simplest, so comparisons are faster. In this case (VARCHAR vs. INT), it will always convert the string type to int.

Also, when coding SQL that has implicit conversions with joins and other operations, it's most likely to generate a different execution plan that the one it would with an explicit conversion.

If you have to compare different types, remember to explicitly cast them, not just for the reason mentioned before but it also says to the next developer that the columns or expressions differ in data type.

SELECT 'OK!' WHERE 'text' = CONVERT(VARCHAR(10), 1)

With some data type you might find unwanted behaviour if you leave implicit conversions.

DECLARE @BitValue1 BIT = NULL
DECLARE @BitValue2 BIT = 1

SELECT
    'Oops!'
WHERE
    ISNULL(@BitValue1, -999) = ISNULL(@BitValue2, -999)

-- Result: Oops! (-999 is being converted to bit, which is 1)

Upvotes: 5

Related Questions