Here are a few rules to keep in mind when working with logical and arithmetic operators in MySQL:
While this may all look quite familiar, be aware that what is true in your programming or scripting language of choice may not be so in MySQL. So, if you encounter what seems to be a bug in using arithmetic operators in a query, it may just be that MySQL behaves a bit differently than what you’re used to. Comparison Operators Like all programming languages, MySQL’s dialect of SQL has a more or less usual set of comparison operators, as well as a few unusual ones. The equals sign ( = ) serves as both the equality operator and the assignment operator, and an expression containing it evaluates to TRUE (1) if the operands are the same, and FALSE (0) if they’re not. If at least one of the operands is NULL , then the result is always NULL . As mentioned in our discussion of datatypes in Chapter 2, a special “null-safe” comparison operator, <=> , returns 1 (TRUE) if the arguments are equal values or if both values are NULL , and 0 (FALSE) otherwise. In other words, 1 <=> 1 returns TRUE (1), 1 <=> NULL returns FALSE (0), and NULL <=> NULL returns TRUE (1). (Remember that the NULL value is not equal to any other value, not even itself.)
There are two ways of writing the inequality comparator. You may use either != or <>; they’re exactly the same so far as MySQL is concerned. The <> notation seems to be more common, and it’s what we prefer to use ourselves, but the choice is entirely up to you. (As always, we recommend you choose one or the other, and stick with it.) Note that NULL compared with any value—even itself—using <> or != yields the null value. However, when performing branching operations, you’re generally checking to see whether a condition is true or not, and since NULL isn’t true, a null result still causes you to follow the “false” branch. We’ll discuss IF() and the other branching operators later in this chapter.
MySQL also has greater-than, less-than, greater-than-or-equal, and less-than-or-equal operators, which are written (in order) >, <, >=, and <=. These behave more or less just as you would expect. As with the equality and inequality operators, any comparison involving NULL and using one of these operators will always yield a NULL result.
There’s also a shortcut for determining whether a given value lies within a certain range. The BETWEEN operator is used as shown here. BETWEEN can also be used with nonnumeric datatypes such as strings. Note that (as usual) string comparisons are case-insensitive unless you employ the BINARY modifier. Dates as well as strings can be compared. If the value immediately before the AND is not less than the value following it, then 0 will be always be returned.
|