What is the use of AND ,OR and NOT operator in SQL?

Understanding the Use of SQL AND, OR, and NOT Operators

Introduction

In SQL (Structured Query Language), we use special words called operators to help us filter and combine data in our databases. Three important operators are AND, OR, and NOT. Let’s learn how to use them.

AND Operator

  • Purpose: The AND operator is used to narrow down search results by combining multiple conditions.
  • Usage: It requires both conditions to be true for a row to be selected.
  • Example: To find employees who are both managers and have a salary above $50,000, you would use AND like this: WHERE job_title = 'Manager' AND salary > 50000.

OR Operator

  • Purpose: The OR operator is used to broaden search results by including rows that meet at least one of the given conditions.
  • Usage: It selects rows where at least one condition is true.
  • Example: To find employees who are either managers or have a salary above $50,000, you would use OR like this: WHERE job_title = 'Manager' OR salary > 50000.

NOT Operator

  • Purpose: The NOT operator is used to exclude rows that meet a specific condition.
  • Usage: It selects rows where the condition is NOT true.
  • Example: To find employees who are not managers, you would use NOT like this: WHERE NOT job_title = 'Manager'.

Combining Operators

  • You can use parentheses to combine these operators and create complex conditions.
  • Example: To find employees who are managers with a salary above $50,000 OR employees with the job title ‘Analyst,’ you can use: WHERE (job_title = 'Manager' AND salary > 50000) OR job_title = 'Analyst'.

Summary

Here’s a quick summary of the use of AND, OR, and NOT operators in SQL:

OperatorPurposeExample
ANDNarrow down resultsWHERE condition1 AND condition2
ORBroaden resultsWHERE condition1 OR condition2
NOTExclude resultsWHERE NOT condition

Remember, these operators help you write powerful SQL queries to retrieve the data you need from your databases effectively.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *