mySQL Order of Operations

mySQL Order of Operations

Imagine holiday season is coming around and you are restocking supplies for your gaming store. Sports games are a hot commodity so you want to search your inventory database for your sports games with low stock using the following query.

SELECT user_id, video_games, puzzles, remaining_stock 
FROM store_inventory 
WHERE remaining_stock < 10
AND video_games like 'FIFA%%' OR video_games like 'MADDEN%%'

This simple SQL statement logically seems like it would select all FIFA and MADDEN titles (ex. FIFA 19, FIFA 20, MADDEN 18) in the table with remaining stock less than 10, however, that is not the case. Instead, you have now restocked your FIFA titles that were low, while overstocking MADDEN titles as the quantity qualifier was not applied. Let’s look at why this happens and how to edit the query in the future. MySQL takes into account AND statements before OR statements in a query. Knowing this, we must ensure the order of operations is correct using parenthesis around the conditional statements. We can modify our original query as follows.

SELECT user_id, video_games, puzzles, remaining_stock 
FROM store_inventory 
WHERE remaining_stock < 10
AND (video_games like 'FIFA%%' OR video_games like 'MADDEN%%')

To summarize the rules we see in this example

Even if            [... WHERE A] 
is the same as     [... WHERE A1 OR A2]
Writing            [...WHERE A AND B] 
is not the same as [...WHERE A1 OR A2 AND B] 
Correct form is   [...WHERE (A1 OR A2) AND B]