Here are few points to keep in mind when comparing values of different types using any of the comparison operators =, <>, !=, >, >=, <, and <=:
Operator Precedence When multiple operators are involved in a single expression, things can get a bit complicated. For example, how should MySQL resolve an expression like 2 + 3 AND 1? Should this evaluate to 3 (3 AND 1 evaluates to 1; 2 + 1 is equal to 3) or to 1 (2 + 3 is equal to 5; 5 AND 1 evaluates as 1)? Of course, you can test this directly, as shown here: However, it isn’t really practical to take the time to do this every time you encounter such an expression, not to mention the fact that, in real life, such expressions are likely to be working with values that aren’t known ahead of time. Fortunately, there’s a set order of precedence that determines which operations are to be done first. The order of precedence for operators in MySQL is almost identical to that found in ANSI SQL. Table 4-2 shows the order of precedence from highest to lowest. Table 4-2. MySQL Operator Precedence
If you want operations to be performed in some other order, you can always force the issue by using parentheses. When evaluating complex expressions involving parentheses, MySQL follows what’s sometimes known as the “inside-outside” rule: operations inside the innermost set(s) of parentheses are performed first, followed by the next set outward, and then by the next set outward from that, and so on. If you’ve written code in practically any other modern programming or scripting language, you should be used to this already. Please check back next week for the second part of this article. |