SQL comparison between boolean values ​​can lead to unexpected results
P粉982009874
P粉982009874 2023-08-18 16:25:41
0
1
562
<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粉982009874
P粉982009874

reply all(1)
P粉513316221

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 相同
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template