0

Having trouble trying to query AND and OR in an SQlite3 statement.

Is there a way where I can do something like

WHERE section = ? AND LEVEL =? AND subj1 =? AND subj2=? AND subj3 =?

From what I see in this particular line

SELECT * FROM students WHERE section = ? AND level =? AND subj1 = ? OR subj2 = ? OR subj3 =?

It won't work because after 'AND subj1 =?' SQlite3 now chooses to select whatever subject that subj2 and subj3 has, completely disregarding the section and level column. How can I get the rows that have match the section, level and subjects that I want?

Here's my code

query = ("""SELECT * FROM students WHERE section = ? AND level =? AND subj1 = ? OR subj2 = ? OR subj3 =?"""
c.execute(query, (variable1, variable2, variable3, variable4, variable5, ))
rows = c.fetchall()
print (rows)   

Here's a sample table

Name        Section       Level        Subject 1       Subject 2      Subject 3

John    |      1      |     1      |      Math     |    Science    |    English
Mary    |      1      |     1      |      Math     |    Science    |    English
Dave    |      2      |     2      |      English  |    History    |    Math 
Joe     |      2      |     2      |      English  |    History    |    Math
        

2 Answers 2

1

OR has lower logical precedence than AND. To do what you want, you need to surround the ORed predicates with parentheses:

SELECT * 
FROM students 
WHERE section = ? AND level = ? AND (subj1 = ? OR subj2 = ? OR subj3 =?)

However, here, it is simpler to use IN:

SELECT * 
FROM students 
WHERE section = ? AND level = ? AND ? IN (subj1, subj2, subj3)
Sign up to request clarification or add additional context in comments.

Comments

0

Use parentheses:

WHERE section = ? AND level =? AND
      (subj1 = ? OR subj2 = ? OR subj3 = ?)

Assuming the last three parameters are the same, you can simplify this using IN:

WHERE section = ? AND level =? AND
      ? IN (subj1, subj2, subj3)

Usually IN has constants in the IN list and column names as the left operand. However, that is not required.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.