Strings and numbers are completely different. Strings are sorted left to right by each character, numbers are assorted in numerical order. This is just one reason why using the correct data type is so important.
'10'
is less than '2'
because '2'
is greater than '1'
; therefore '10'
is less than '2'
. '09-12-2019'
is "before" '31-01-1924'
because '3'
is greater than '0'
.
If you are comparing numbers, use numerical data types, not strings. If you're comparing dates (and times) use a Date and Time data type, not a string.
Appears what the OP is actually asking about it Data Type Precedence. When 2 expressions are of different data types and compared the Data Precedence is used to implicitly convert one side of the expression to be the same as the other.
In your query you have 2 expressions: @qav1 < '0'
and @qav1 < 0
. The former will not be effected by Data Type Precedence, as both sides are the same. As a result the -
is compared to the 0
, which has a larger value , and so 1
is returned.
For the second second expression, '-89'
is implicitly converted to an int
, due to Data Type Precedence, and so the expression beomces -89 < 0
. This is true, and so 1
is returned.
SQL Server uses the following precedence order for data types:
- user-defined data types (highest)
- sql_variant
- xml
- datetimeoffset
- datetime2
- datetime
- smalldatetime
- date
- time
- float
- real
- decimal
- money
- smallmoney
- bigint
- int
- smallint
- tinyint
- bit
- ntext
- text
- image
- timestamp
- uniqueidentifier
- nvarchar (including nvarchar(max) )
- nchar
- varchar (including varchar(max) )
- char
- varbinary (including varbinary(max) )
- binary (lowest)