SQL AND, OR and NOT Operators
SQL AND, OR and NOT operators are used to combine and test multiple conditions for data in SQL. AND, OR and NOT operators can combine with WHERE clauses.
The AND Operator:
AND Operator display records if all the condition separated by AND evaluates to be true.
AND Operator Syntax :
The syntax of the AND Operator is −
SELECT column1, column2, columnN FROM table_name WHERE [condition1] AND [condition2]...AND [conditionN];
The OR Operator:
OR Operator display records if any one of the condition separated by OR evaluates to be true.
OR Operator Syntax :
The syntax of the OR Operator is −
SELECT column1, column2, ... FROM table_name WHERE condition1 OR condition2... OR conditionN;
The NOT Operator:
NOT Operator display records if the condition evaluates to be not true.
NOT Operator Syntax :
The syntax of the NOT Operator is −
SELECT column1, column2, ... FROM table_name WHERE NOT condition;
AND, OR and NOT Operator Example :
Consider the Customer table with the following records -
CustomerID | CustomerName | Age | Address | CustomerSalary |
---|---|---|---|---|
1 | Aarav | 28 | Udaipur | 28000 |
2 | Vivaan | 25 | Mumbai | 30000 |
3 | Reyansh | 28 | Chennai | 35000 |
4 | Muhammad | 24 | Udaipur | 50000 |
5 | Sai | 30 | Mumbai | 27000 |
AND Example:- The following code is an example, which would fetch the all fields from Customer table where Address is Udaipur AND Age is 24 (means both the condition must be true).
SELECT * FROM Customer WHERE Address='Udaipur' AND Age=24;
The result for the respective sql query is as follows −
CustomerID | CustomerName | Age | Address | CustomerSalary |
---|---|---|---|---|
4 | Muhammad | 24 | Udaipur | 50000 |
OR Example:- The following code is an example, which would fetch the all fields from Customer table where Address is Udaipur OR Age is 24 (means any one of the condition must be true).
SELECT * FROM Customer WHERE Address='Udaipur' OR Age=24;
The result for the respective sql query is as follows −
CustomerID | CustomerName | Age | Address | CustomerSalary |
---|---|---|---|---|
1 | Aarav | 28 | Udaipur | 28000 |
4 | Muhammad | 24 | Udaipur | 50000 |
NOT Example:- The following code is an example, which would fetch the all fields from Customer table where Address is NOT Udaipur(means the condition must be NOT true).
SELECT * FROM Customer WHERE NOT Address='Udaipur';
The result for the respective sql query is as follows −
CustomerID | CustomerName | Age | Address | CustomerSalary |
---|---|---|---|---|
2 | Vivaan | 25 | Mumbai | 30000 |
3 | Reyansh | 28 | Chennai | 35000 |
5 | Sai | 30 | Mumbai | 27000 |
Visit :
Discussion