Need help from an expert?
The world’s top online tutoring provider trusted by students, parents, and schools globally.
The NOT IN operator in SQL is used to exclude certain values in a WHERE clause of a query.
The NOT IN operator in SQL is a logical operator that allows you to select only rows that do not match values in a list. It is used in the WHERE clause of a SELECT, UPDATE, or DELETE statement. The syntax for using the NOT IN operator in SQL is: column_name NOT IN (value1, value2, ... value_n).
For instance, if you have a table named 'Students' with a column 'Grade' and you want to select all students who are not in Grade 10 or 11, you would write the query as follows:
SELECT * FROM Students WHERE Grade NOT IN (10, 11);
This query will return all rows from the 'Students' table where the 'Grade' is not 10 or 11.
The values in the parentheses after NOT IN can be a list of values separated by commas, or a subquery that returns a list of values. For example, if you have another table named 'Teachers' and you want to select all students who are not taught by teachers with the IDs 1, 2, or 3, you could write the query as follows:
SELECT * FROM Students WHERE TeacherID NOT IN (SELECT TeacherID FROM Teachers WHERE TeacherID IN (1, 2, 3));
This query will return all rows from the 'Students' table where the 'TeacherID' is not in the list of 'TeacherID's returned by the subquery.
Remember, the NOT IN operator is a very powerful tool in SQL, but it should be used carefully. It can make your queries more complex and potentially slower, especially when used with subqueries. Always test your queries to ensure they return the expected results and perform well.
Study and Practice for Free
Trusted by 100,000+ Students Worldwide
Achieve Top Grades in your Exams with our Free Resources.
Practice Questions, Study Notes, and Past Exam Papers for all Subjects!
The world’s top online tutoring provider trusted by students, parents, and schools globally.