The SQL AND and OR operators are used to combine multiple conditions to narrow data in an SQL statement.
These two operators are called conjunctive operators. These operators provide a means to make multiple comparisons with different operators in the same SQL statement.
The AND Operator: The AND operator allows the existence of multiple conditions in an SQL statement’s WHERE clause.
Syntax: The basic syntax of AND operator with WHERE clause is as follows:
SELECT column1, column2, columnN FROM table_name WHERE [condition1] AND [condition2]…AND [conditionN];
You can combine N number of conditions using AND operator. For an action to be taken by the SQL statement, whether it be a transaction or query, all conditions separated by the AND must be TRUE.
Example: Consider the DEPT table having the following records:
deptno | dname | location |
10 | Accounting | New York |
20 | Research | Dallas |
30 | Sales | Chicago |
40 | Operations | Boston |
Following is an example, which would fetch deptno, dname and location fields from the DEPT table where deptno is greater than 20 AND location is Boston:
SELECT deptno, dname, location FROM DEPT WHERE deptno > 20 AND location = 'Boston';
This would produce the following result:
deptno | dname | location |
40 | Operations | Boston |
The OR Operator: The OR operator is used to combine multiple conditions in an SQL statement’s WHERE clause
Syntax: The basic syntax of OR operator with WHERE clause is as follows:
SELECT column1, column2, columnN FROM table_name WHERE [condition1] OR [condition2]...OR [conditionN] ;
You can combine N number of conditions using OR operator. For an action to be taken by the SQL statement, whether it be a transaction or query, only any ONE of the conditions separated by the OR must be TRUE.
Example: Consider the DEPT table having the following records:
SELECT deptno, dname, location FROM DEPT WHERE deptno > 20 or location = 'Boston';
This would produce the following result:
deptno | dname | location |
30 | Sales | Chicago |
40 | Operations | Boston |