0

This is the silly question but please help me out of the loop.

SELECT * 

FROM TABLE_NAME T1

WHERE '10000' > '2'

Why the condition above is false ? I know I can cast it into Number but I don'n know why the condition above is not true. Thank you very much.

4 Answers 4

2

If you try

WHERE 'A' < 'B'

it gives you true

If you try

WHERE 'AAAAAB' > 'AAAAAA'

it returns true ,since B is greater than A

For the same reason WHERE '10000' > '2' return false

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, but then again. Why '30000' < '2' is FALSE. I think they may compare the first char then ignore the rest ???
It compare first character of '3000' which is 3 with first character of '2' which 2, Now 3 < 2 return false because ASCII code of 2 is less than 3
@iamdeowanshi the comment you gave here is the real reason ; I suggest, especially since this is already the accepted answer, to add that to the actual answer. ABC is alphabetically before DEFG ; but clearly a four-digit number is greater than a 3-digit number. Alphabetically we go by the first letter first, whereas numerically we would pad leading zeroes before doing such a comparison.
2

The condition is false because the values are compared as strings, not numbers. The same reason that:

WHERE 'A0000' > 'B'

evaluates to false.

The moral? Only use single quotes for string and date constants. Do not use single quotes for numbers.

2 Comments

Thank you for your reply but I have a further question. Then why the 'A0000' < 'B' return TRUE ? I want to know how they compared with each other.
@PhamNgocVinh . . . Because the comparison is alphabetical, like entries in a dictionary.
1

Numeric types and strings are treated differently.

example)

1 < 2 is TRUE

'1000'>'2' is FALSE

The character type changes to a numeric type when compared.

using 49 instead of '1' and using 50 instead of '2'

result 49 > 50 = FALSE

if '1000' > '1', is TRUE

See the ASCII code.

Comments

1

Just think simply. As it is all, Char type have values on ascii system or charset collation.

Just for example :

Declare @a char(1)='A',@b char(1)=B,@c char(1)='C'

a value is 1 b value is 2 c value is 3

It's just alphabetically order for char based variables on Sql server.

This means if you compare char, nchar, varchar or nvarchar values, program first of all examines value your first index, after then second... Till that end.

Comments

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.