search

Home  >  Q&A  >  body text

SQL comparison between boolean values ​​can lead to unexpected results

<p>Why do most (all?) SQL databases give the following results: </p> <pre class="brush:php;toolbar:false;">SELECT FALSE < FALSE; -- FALSE / 0 Ok SELECT TRUE < FALSE; -- FALSE / 0 Ok SELECT NOT(FALSE) < FALSE; -- TRUE / 1 What? SELECT NOT(TRUE) < FALSE; -- TRUE / 1 What? ? </pre> <p>Just to double-check: </p> <pre class="brush:php;toolbar:false;">SELECT NOT(TRUE) = FALSE; -- TRUE / 1 Ok SELECT NOT(FALSE) = TRUE; -- TRUE / 1 Ok</pre> <p>In Postgres I can also check: </p> <pre class="brush:php;toolbar:false;">SELECT pg_typeof(TRUE), pg_typeof(NOT(FALSE)); -- boolean | boolean</pre> <p>I've tried PostgreSQL, SQLite3 and MariaDB and they all gave the same unexpected results. </p><p> <strong>What am I missing? </strong></p>
P粉982009874P粉982009874462 days ago565

reply all(1)I'll reply

  • P粉513316221

    P粉5133162212023-08-19 09:07:28

    I'm not sure how NOT(FALSE) is evaluated, but NOT is not a function. If you want to negate a boolean literal, then parentheses should be placed around the entire expression, i.e. use (NOT FALSE) instead of NOT(FALSE). Consider the following example:

    SELECT (NOT FALSE) < FALSE; -- 0,与 TRUE < FALSE 相同
    SELECT (NOT TRUE) < FALSE; -- 0,与 FALSE < FALSE 相同
    

    reply
    0
  • Cancelreply