OR operator in SQL Server

The OR operator in SQL Server is used to combine two or more conditions in a WHERE clause. It returns true if any of the conditions are true. Here is an example of how to use the OR operator in SQL Server:

Syntax: –

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

Examples,

The OR operator can be used with other operators such as LIKE, IN, and BETWEEN. For example, the following SQL statement selects all customers from Spain or Mexico whose name starts with the letter ‘G’:

SELECT * FROM Customers
WHERE Country = \'Spain\' OR Country = \'Mexico\' AND CustomerName LIKE \'G%\';

In this example, the AND operator has a higher precedence than the OR operator. To ensure that the correct results are returned, we need to use parentheses to group the conditions:

SELECT * FROM Customers

WHERE (Country = \'Spain\' OR Country = \'Mexico\') AND CustomerName LIKE \'G%\';

IN operator in SQL Server

  • The IN operator in SQL Server is used to specify multiple values in a WHERE clause. It allows you to test whether a specified value matches any value in a list. IN operator is a shorthand for multiple OR conditions.

 Here is an example of how to use the IN operator in SQL Server:

Syntax: –

SELECT column_name(s) FROM table_name
WHERE column_name IN (value1, value2, …);

OR

SELECT column_name(s) FROM table_name
WHERE column_name IN (SELECT STATEMENT);

The IN operator can be used with a subquery in the WHERE clause. With a subquery, you can return all records from the main query that are present in the result of the subquery. Here is an example of how to use the IN operator with a subquery:

SELECT *

FROM Customers

WHERE CustomerID IN (SELECT CustomerID FROM Orders);

For Examples: –

  1. The following SQL statement selects all customers that are located in \”Germany\”, \”France\” or \”UK\”:

SELECT * FROM Customers WHERE Country IN (\’Germany\’, \’France\’, \’UK\’);

  • The following SQL statement selects all customers that are NOT located in \”Germany\”, \”France\” or \”UK\”:

SELECT * FROM Customers WHERE Country NOT IN (\’Germany\’, \’France\’, \’UK\’);

  • The following SQL statement selects all customers that are from the same countries as the suppliers:

SELECT * FROM Customers WHERE Country IN (SELECT Country FROM Suppliers);