Why is ' 2' > '10'?

后端 未结 2 1066
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-07 04:12

Why is \' 2\' with an initial space bigger than \'10\'?

select \' 2\' > \'10\';
 ?column? 
----------
 t
(1 row)

I tried i

2条回答
  •  无人共我
    2021-02-07 04:40

    I think PostgreSQL automatically tries to figure out the type behind the scenes and in Linux it tries to get rid of the ' ', some of the comparisons are also based on locale.

    • Thus, ' 2' > '10' becomes '2'>'10' and the comparison is '2'>'1'; they are not equal, so no need to continue with the rest of the string, and ascii('2') is greater than ascii('1'), so it evaluates to true.

    • If it were an equality operation (e.g. ' 22' = '22 ') it would result to false because Postgres does a byte by byte comparison. This is important because the engine uses two different algorithms when doing comparisons.

    • If you specify the type via typecasting, then it won't override the space rules (' '=>'').


    Also credit goes to: RhodiumToad and Peerce in #postgresql

提交回复
热议问题