The AND/OR operators are used to create an SQL statement based on 2 or more conditions in SQL WHERE clause. They can be used in SELECT, UPDATE, DELETE or INSERT statement.
The AND operator selects records if all the conditions in WHERE clause are true at the same time. The OR operator selects records if any conditions in the WHERE clause are true.
Syntax
SELECT columns FROM tables WHERE condition1 {[AND|OR] condition2}+
The {}+ means that we can repeat it one or more times.
Note: We can indicate the order of the conditions by using the parenthesis sign ().
Examples
Table: Employees
EmployeeId | FirstName | LastName | Department | Salary |
---|---|---|---|---|
203 | Mazojys | Fxoj | Finance | 78000 |
204 | Jozzh | Lnanyo | Finance | 45800 |
205 | Syllauu | Dfaafk | Finance | 57000 |
206 | Gecrrcc | Srlkrt | Finance | 62000 |
302 | Jssme | Bdnaa | Development | 75000 |
303 | Dnnaao | Errllov | Development | 55000 |
304 | Tyoysww | Osk | Development | 49000 |
We want to select an employee whose first name is Syllauu and last name is Dfaafk:
SELECT * FROM Employees WHERE FirstName='Syllauu' AND LastName='Dfaafk'
The result will look like:
EmployeeId | FirstName | LastName | Department | Salary |
---|---|---|---|---|
205 | Syllauu | Dfaafk | Finance | 57000 |
We want to select employees whose last name is Lnanyo or Bdnaa:
SELECT * FROM Employees WHERE LastName='Lnanyo' OR LastName='Bdnaa'
The result will look like:
EmployeeId | FirstName | LastName | Department | Salary |
---|---|---|---|---|
204 | Jozzh | Lnanyo | Finance | 45800 |
302 | Jssme | Bdnaa | Development | 75000 |
Now we put a little bit more conditions:
SELECT * FROM Employees WHERE Department='Finance' AND (LastName='Lnanyo' OR LastName='Bdnaa')
The result will look like:
EmployeeId | FirstName | LastName | Department | Salary |
---|---|---|---|---|
204 | Jozzh | Lnanyo | Finance | 45800 |