codingstreets
Search
Close this search box.

Get Started: SQL Operators – AND, OR and NOT

In This Article You Will Know About SQL Operators. 

SQL Operators – Before moving ahead, let’s know a bit about SQL WHERE Clause.

Table of Contents

SQL AND, OR, and NOT Operators

The WHERE clause is easily useable with AND, OR, and NOT operators.

AND: The AND operator is used to return the answer between the specified conditions if the condition met TRUE.

OR: The OR operator is used to return the answer between the specified conditions if any of the given conditions met TRUE.

NOT: The NOT operator returns the answer if the condition is FALSE.

Example Database

Below is the example of a database table named “details.”

Id

Name

Class

section_id

1

Alex

5

1

2

Rolex

6

2

3

Salex

7

2

4

Lelex

8

3

5

Kelex

9

5

AND Syntax

SELECT column1, column2, …
FROM table_name
WHERE condition1 AND condition2 AND condition3 …;

AND Examples

Example: Use AND operator to return answer, if both conditions met TRUE.

				
					SELECT * FROM details
WHERE name='Alex' AND name='Kelex';

				
			

Example: Use AND operator to return answer, if both conditions met TRUE.

				
					SELECT class 
FROM details
WHERE section_id=2 AND section_id=5;

				
			

OR Syntax

SELECT column1, column2, …
FROM table_name
WHERE condition1 OR condition2 OR condition3 …;

OR Examples

Example: Use OR operator to return answer, if any of given conditions met TRUE.

				
					SELECT * FROM details
WHERE name='Alex' OR name='Kelex';
				
			

Example: Use OR operator to return answer, if any of given conditions met TRUE.

				
					SELECT class 
FROM details
WHERE section_id = 5 OR section_id = 8;
				
			

NOT Syntax

SELECT column1, column2, …
FROM table_name
WHERE NOT condition;

NOT Examples

Example: Use OR operator to return answer, if any of given conditions met TRUE.

				
					SELECT * FROM details
WHERE NOT name = 'Alex';
				
			

Example: Use OR operator to return answer, if any of given conditions met TRUE.

				
					SELECT class 
FROM details
WHERE NOT section_id = 2;

				
			

Combination of AND, OR, and NOT operator

SQL allows us to use AND, OR, and NOT operator together at once.

Example: Use AND, OR, and NOT operator to return answer, if specified conditions met TRUE.

				
					SELECT * FROM details
WHERE name = 'Alex' AND (class= 5 OR class=8);

				
			

Example: Use AND, OR, and NOT operator to return answer, if specified conditions met TRUE.

				
					SELECT name 
FROM details
WHERE NOT name = 'Alex' AND (class= 2 OR class=8);

				
			

If you find anything incorrect in the above-discussed topic and have further questions, please comment below.

Connect on:

Recent Post

Popular Post

Top Articles

Archives
Categories

Share on