# Operator Precedence in MySQL

Contents

In this article, you will learn about operator precedence in MySQL.

## Operator precedence in MySQL

Operator precedence in MySQL determines the order in which operators are evaluated in an expression.

### Operator precedence rules

MySQL follows the same operator precedence rules as most programming languages, where certain operators are evaluated before others. The following is the order of operator precedence in MySQL, from highest to lowest:

- Parentheses: ()
- Unary operators: – (negative), + (positive), NOT
- Multiplicative operators: * (multiplication), / (division), % (modulus)
- Additive operators: + (addition), – (subtraction)
- Comparison operators: =, <, >, <=, >=, <> (not equal to), != (not equal to)
- Logical operators: AND, OR

### Examples of operator precedence

Let’s consider the following example:

```
SELECT 10 + 5 * 2;
```

What is the result of this expression? According to the operator precedence rules, multiplication takes precedence over addition, so the expression is evaluated as follows:

`SELECT 10 + (5 * 2);`

Which evaluates to:

`SELECT 10 + 10;`

And the final result is:

`20`

### Using parentheses to override operator precedence

You can use parentheses to override the default operator precedence and control the order in which expressions are evaluated. For example:

`SELECT (10 + 5) * 2;`

In this expression, the parentheses force the addition operation to be evaluated first, and then the multiplication operation, resulting in a final result of 30.

### Example of operator precedence with logical operators

Logical operators have a lower precedence than comparison operators, so be careful when using them together. For example:

`SELECT 1 > 2 OR 3 > 2 AND 4 < 5;`

What is the result of this expression? According to the operator precedence rules, the AND operator takes precedence over the OR operator, so the expression is evaluated as follows:

`SELECT 1 > 2 OR (3 > 2 AND 4 < 5);`

Which evaluates to:

`SELECT 0 OR 1;`

And the final result is:

`1`

To avoid confusion, it's always a good idea to use parentheses to clarify the order in which expressions are evaluated.