5

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?

3
  • 5
    You should avoid implicit conversions. And compare directly to id=7 Commented Jun 5, 2018 at 9:34
  • 3
    If you want to know what kind of trouble conversions can bring, try the reverse: where name=3, with name a string column, will give errors when the contents of name are converted to int, due to the bizarre precedence rules SQL Server has for implicit conversions. Commented Jun 5, 2018 at 9:35
  • 4
    To add to @JeroenMostert 's comment: Data type precedence (Transact-SQL). Although, not sure I agree with the "bizarre" statement. :) Commented Jun 5, 2018 at 9:38

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

1 Comment

You should also mention that improper use of types can affect optimization, such as the use of indexes, table statistics, and partitions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.