Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ms Sql Server Compare Numeric column with string value

Tags:

sql

sql-server

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?

like image 744
Husam Zidan Avatar asked Jun 05 '18 09:06

Husam Zidan


People also ask

How do I compare numeric values in SQL?

SQL Equal to ( = ) operator The equal to operator is used for equality test within two numbers or expressions.

How do I compare values in two columns in SQL?

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.

How do I compare strings in MS SQL?

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.

How do you compare variables in SQL?

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.


1 Answers

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)
like image 173
EzLo Avatar answered Oct 06 '22 00:10

EzLo