SQL WHERE Clause in MS SQL Server

In SQL, we don’t always need all data. We need filtered data. For that, we use the WHERE Clause.
WHERE clause is like the Filter in Excel.
Syntax

SELECT column1, column2
FROM table_name
WHERE condition;

Let’s take a sample table Employees for all examples:

IDNameCitySalaryDept
1RakeshNoida75000IT
2AmitDelhi45000HR
3PriyaNoida80000IT

1. WHERE with = (Equal to)

— Get all employees from Noida
SELECT * FROM Employees WHERE City = ‘Noida’;

2. WHERE with > , < , <> (Comparison)

— Salary greater than 50000
SELECT * FROM Employees WHERE Salary > 50000;

— Not from Delhi
SELECT * FROM Employees WHERE City <> ‘Delhi‘;

3. WHERE with AND, OR

— City is Noida AND Salary > 70000
SELECT * FROM Employees WHERE City = ‘Noida’ AND Salary > 70000;

— City is Delhi OR Noida
SELECT * FROM Employees WHERE City = ‘Delhi’ OR City = ‘Noida’;

4. WHERE with IN Operator
Instead of writing many OR, use IN. Very useful.

SELECT * FROM Employees WHERE City IN (‘Noida’, ‘Delhi’, ‘Gurgaon’);

5. WHERE with BETWEEN (Range)

— Salary between 40000 to 80000

SELECT * FROM Employees WHERE Salary BETWEEN 40000 AND 80000;

6. WHERE with LIKE (Search)
This is most important for Data Analysts.

— Name starts with R
SELECT * FROM Employees WHERE Name LIKE ‘R%’;

— City contains ‘oida’
SELECT * FROM Employees WHERE City LIKE ‘%oida%’

;

7. WHERE with NOT

— Employees NOT in HR
SELECT * FROM Employees WHERE Dept NOT IN (‘HR’);

Common Mistake in MS SQL Server
New users forget single quotes for text.
Wrong: WHERE City = Noida
Correct: WHERE City = ‘Noida’

Numbers don’t need quotes: WHERE Salary = 75000

Conclusion
WHERE Clause is 80% of SQL. If you master WHERE with AND, OR, IN, BETWEEN, LIKE – you can solve any interview query.
Practice Task: Write a query to get all IT department employees from Noida whose salary is more than 60000.
Answer in comments!

Leave a Comment

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

Scroll to Top