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?
SQL Equal to ( = ) operator The equal to operator is used for equality test within two numbers or expressions.
In SQL, problems require us to compare two columns for equality to achieve certain desired results. This can be achieved through the use of the =(equal to) operator between 2 columns names to be compared.
MS Access StrComp() Function The result is returned as an integer based on the comparison: If string1 = string2, this function returns 0. If string1 < string2, this function returns -1. If string1 > string2, this function returns 1.
You can easily compare variables using INTERSECT as it is NULL -sensitive: DECLARE @A BIT = NULL ,@B BIT = 1; IF EXISTS ( SELECT @A INTERSECT SELECT @B ) SELECT 'equal'; ELSE SELECT 'not equal'; Also, when you need to do such comparisons in complex queries, this could improve performance as it allows using indexes.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With