Problems encountered in the execution order of AND and OR in SQL statement

  • 2021-12-04 20:09:52
  • OfStack

Problem

Yesterday, I encountered a problem when writing the database SQL. The root of the problem lies in the execution priority of the AND and OR keywords of the SQL statement. The following is a test for this problem.

Scene

1. There is a student table Student, and the table fields include Id (user primary key), Name (user name), Grade (grade), Class (class) and Sex (gender). As follows:

Table structure

2. Import 10 pieces of test data into the table, as follows:

Table data

3. It is necessary to find out the female students in Grade 1 or Class 2 who are female. The SQL statement is as follows:
select * from student where sex= 'Female' and grade=1 or class=2
However, the results of the sql query do not meet the requirements, and the execution results are as follows:

Execution results

Male students with class 2 were also found in the execution results, which was obviously incorrect.

4. Modify the lower SQL statement and add parentheses. As follows:


select * from student where sex=' Female ' and (grade=1 or class=2)

The results of the sql query meet the requirements

Analysis

From the above scenario, the crux of the problem lies in the execution order of AND and OR.
Looking up data, the priority of relational operators is: NOT > AND > OR
If OR is followed by where, OR automatically separates the left and right query conditions.
As in statement 1 in the above scenario, his query criteria are divided into two parts (or):


1 , sex=' Female ' and grade=1
2 ,  class=2

This is to find out the female students in Grade 1 and the students in Class 2. Does not meet the requirements of the original query.
The solution is to use parentheses to distinguish the order of execution
As in statement 2 of the above scenario, the query criteria are divided into two parts (and):


1 ,  sex=' Female ' 
2 ,  (grade=1 or class=2)


Related articles: