While learning some SQL, I stumbled upon this seemingly incorrect clause:
SELECT item
FROM inventory
WHERE 20 => price < 500;
The query does not result what was intended and should look like this:
SELECT item
FROM inventory
WHERE price => 20 AND price < 500;
I know that there is a better way to solve this. What really interests me here is why is the first query showed not failing at all? It returns results, sure not the ones we want but I expected it to fail completely.
Can someone help me to understand what the first query does at all? I couldn’t find any useful information.
2
Answers
MySQL comparison operators return 0 or 1 (or null), and that return itself can be used in a comparison.
is doing the comparison 20 >= price, then seeing if the 0 or 1 or null is < 500 (which it will be, unless price is null). So the overall expression will be either 1 (true) or null.
Assuming this is a copying error and the first comparison operator is actually
>=
, the expressionis equivalent to
because of operator precedence. In MySQL, boolean values are the integers 1 (for TRUE) and 0 (for FALSE). So if
20 >= price
is true, it’s equivalent toIf that part if false, it’s equivalent to
Either way, the combined condition will be true, so the
WHERE
condition will result in all rows being returned.There are some languages where you can write expressions like this; Python allows "chained comparisons", automatically treating them as combined with
and
. So one can writeto test if the price is between 20 and 500. SQL doesn’t have this, but it does have a built-in
BETWEEN
operator:(since
BETWEEN
is inclusive, you have to subtract to get the equivalent of<
instead of<=
).The original code is also nonsensical for another reason: If a number is less than 500, it will also be less than or equal to 20. So
20 >= price
is redundant. Are you sure it wasn’t20 <= price
(I notice that you swapped the order of arguments to>=
when you wrote the "corrected" version)?