Logical Operations in SQL Query in Python

In the selection condition, you can make more complex combinations using the OR and AND ​​commands. They work the same way as their Python counterparts, the if construct. Let's look at some examples.

Example

Let's select users with a salary of 500 and an age of 23 years:

pythonquery = "SELECT * FROM users WHERE salary=500 AND age=23"

The result of the executed code:

python{'id': 3, 'name': 'user3', 'age': 23, 'salary': 500}

Example

Let's select users with a salary of 500 OR age of 23 years:

pythonquery = "SELECT * FROM users WHERE salary=500 OR age=23"

The result of the executed code:

python{'id': 1, 'name': 'user1', 'age': 23, 'salary': 400}
{'id': 2, 'name': 'user2', 'age': 25, 'salary': 500}
{'id': 3, 'name': 'user3', 'age': 23, 'salary': 500}
{'id': 5, 'name': 'user5', 'age': 27, 'salary': 500}

Example

Let's select users with a salary from 450 to 900:

pythonquery = "SELECT * FROM users WHERE salary>450 AND salary<900"

The result of the executed code:

python{'id': 2, 'name': 'user2', 'age': 25, 'salary': 500}
{'id': 3, 'name': 'user3', 'age': 23, 'salary': 500}
{'id': 5, 'name': 'user5', 'age': 27, 'salary': 500}

Example

Let's select users aged from 23 to 27 years inclusive:

pythonquery = "SELECT * FROM users WHERE age>=23 AND age<=27"

The result of the executed code:

python{'id': 1, 'name': 'user1', 'age': 23, 'salary': 400}
{'id': 2, 'name': 'user2', 'age': 25, 'salary': 500}
{'id': 3, 'name': 'user3', 'age': 23, 'salary': 500}
{'id': 5, 'name': 'user5', 'age': 27, 'salary': 500}

Example

Complex combinations of OR and AND ​​commands can be grouped using parentheses to show precedence of conditions:

pythonquery = "SELECT * FROM users WHERE (age<20 AND age>27) OR (salary>300 AND salary<500)"

The result of the executed code:

python{'id': 1, 'name': 'user1', 'age': 23, 'salary': 400}

Practical tasks

Задание 1

Select users aged between 25 (not inclusive) and 28 (inclusive).

Задание 2

Select user user1.

Задание 3

Select users user1 and user2.

Задание 4

Select everyone except user user3.

Задание 5

Select all users aged 27 years or with a salary of 1000.

Задание 6

Select all users aged 27 years or with a salary not equal to 400.

Задание 7

Select all users aged between 23 years (inclusive) and 27 years (exclusive) or with a salary of 1000.

Задание 8

Select all users aged between 23 years and 27 years or with a salary between 400 and 1000.