Logical Operations in SQL Query in PHP

In the selection condition, more complex combinations can be made using the commands OR and AND. They work the same way as their analogs in the PHP if construct. Let's look at some examples.

Example

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

php<?php
  $query = "SELECT * FROM users WHERE salary=500 AND age=23";
?>

Example

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

php<?php
  $query = "SELECT * FROM users WHERE salary=500 OR age=23";
?>

Example

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

php<?php
  $query = "SELECT * FROM users WHERE salary>450 AND salary<900";
?>

Example

Let's select users with an age from 23 to 27 years inclusive:

php<?php
  $query = "SELECT * FROM users WHERE age>=23 AND age<=27";
?>

Example

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

php<?php
  $query = "SELECT * FROM users WHERE (age<20 AND age>27) OR (salary>300 AND salary<500)";
?>

Practical Tasks

Задание 1

Select users aged from 25 (exclusive) to 28 years (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 from 23 years (inclusive) to 27 years (exclusive) or with a salary of 1000.

Задание 8

Select all users aged from 23 years to 27 years or with a salary from 400 to 1000.