SQL comparison between boolean values can lead to unexpected results
P粉982009874
2023-08-18 16:25:41
<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>
I'm not sure how
NOT(FALSE)
is evaluated, butNOT
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 ofNOT(FALSE)
. Consider the following example: