SQL can be very simple

Be careful when using multiple AND statements and/or using OR statements as well — it’s prudent to use parentheses since if you exclude parentheses, it may change the outcome as a result of how SQL evaluates each AND and OR condition.

Assume you want data from the right where the state is CA or TX and the 2022 estimate is at least 2 million.

Query 1:

SELECT *

FROM database_table

WHERE ST = ‘CA’ or ST = ‘TX‘ and 2022 estimate > 2,000,000

Query 2:

SELECT *

FROM database_table

WHERE (ST = ‘CA’ or ST = ‘TX‘) and 2022 estimate > 2,000,000

  • The first SQL statement above returns data for all States equal California or Texas, and then looks at all rows having 2022 estimate above 2 million. So, it will return a row for El Paso for ex, since that fits the criteria “ST = ‘TX’ “ since it does not have extra parentheses to be more specific.

  • The second SQL statement is correct — it will first filter for the states of California or Texas because there are parentheses, and then filter this sub-list of CA/TX states for those cities having a 2022 estimate above 2 million. It returns the desired result (of only Los Angeles and Houston, and exclude El Paso) since the parentheses ensure that we first look at the states, and then apply the 2nd filter.