0

I have seen that greater than and less than operators can be applied on string values in SQL Server but I haven't figured out yet what logic is being applied here behind the scenes to perform the comparison.

For example, the string value 'Gabriel' is greater than 'Cassandra':

SELECT 1 WHERE 'Gabriel' > 'Cassandra'

The query above returns 1, whereas an empty result set is returned if the comparison operator is changed to '<'.

Dale K
  • 25,246
  • 15
  • 42
  • 71
tteguayco
  • 766
  • 1
  • 6
  • 16
  • 5
    They work according to [collation rules](https://learn.microsoft.com/sql/relational-databases/collations/collation-and-unicode-support). These can be fairly complex; for example, some control characters won't participate in comparison at all under most collations. Binary collations compare according to how the characters are encoded (which is also specified by the collation). – Jeroen Mostert Jan 21 '21 at 20:18
  • Alphabetical order you mean? – tteguayco Jan 21 '21 at 20:19
  • It works the same way as `ORDER BY` on a string column works. Strings that compare as greater will be ordered later – Martin Smith Jan 21 '21 at 21:12
  • 1
    Does this answer your question? [SQL string comparison, greater than and less than operators](https://stackoverflow.com/questions/26080187/sql-string-comparison-greater-than-and-less-than-operators) – Heinzi Jan 21 '21 at 21:55

1 Answers1

-1

The comparison is alphabatical, so 'B' is greater than 'A', and 'C' is greater than 'B' and so on.