SQL Server WHERE IN – SQL Server WHERE and IN clauses are two different SQL conventions are used in conjunction majorly.
Let’s look at the usage of WHERE clause and IN operator separately with example queries.
What is WHERE Clause
- WHERE clause in SQL is used to filter out/restrict the Number of Results/Rows/Records returned by the SELECT Query.
- WHERE clause, when used, must contain at least One logical condition/criteria.
- WHERE is an Optional Clause in SQL. You may not use it until and unless you wish to restrict certain rows/results.
- When an SQL Query does not contain a WHERE Clause, then the Query is called as Open Select.
WHERE Clause Example
Let us assume you have an SQL Table with 50 Students and their Subject-wise marks scored. And, you would like to see the Students only who have scored more than 90 in ENGLISH.
The below SELECT Query has 2 logical conditions in the WHERE clause separated by keyword AND.
SELECT STUDENT_NAME, STUDENT_NO, MARKS_SCORED FROM STUDENT_MARKS WHERE SUBJECT = "ENGLISH" AND MARKS_SCORED > 90;
What is IN Operator
- IN in SQL Server is a Logical Operator which is used to check if a given value falls in any of the provided list of values.
- IN operator is always denoted by open parentheses and close parenthesis ( ). The list of values are separated by Comma(,)
- The list of values given inside the ( ) parentheses can be of any data-type and in any data-length and they must match the data-type of the table-column / literal / field-name
IN Operator Example
In the above Student and Marks example, assume you want to see the Students from Classes 10th and 12th.
The below SELECT Query has 3 logical conditions in the WHERE clause separated by keyword AND and the last logical condition is defined using an IN operator.
SELECT STUDENT_NAME, STUDENT_NO, MARKS_SCORED FROM STUDENT_MARKS WHERE SUBJECT = "ENGLISH" AND MARKS_SCORED > 90 AND CLASS IN ("10", "12");
Thank you for reading.
Please visit https://www.sql-scripts.com for anything that is related SQL Queries, Scripts and How to stuffs.