WHERE ClauseThe WHERE clause is used to filter records in SQL queries. It specifies the condition that must be met for the rows to be included in the query result. You can use WHERE with SELECT, UPDATE, and DELETE statements to decide which rows are returned or affected.
? Goal: Filter rows
WHERE: Adds a condition to filter the result set.AND: Combines multiple conditions; all must be true.OR: Combines conditions; at least one must be true.NOT: Reverses the result of a condition.BETWEEN: Selects values within a specific range (inclusive).!= or <>: Checks for inequality.SELECT, UPDATE and DELETE queries.
-- Basic WHERE syntax in a SELECT query
SELECT column1, column2, ...
FROM table_name
WHERE condition;
-- WHERE with multiple conditions (AND)
SELECT column1, column2
FROM table_name
WHERE condition1 AND condition2;
-- WHERE with OR condition
SELECT column1, column2
FROM table_name
WHERE condition1 OR condition2;
-- WHERE with NOT condition
SELECT column1, column2
FROM table_name
WHERE NOT condition;
-- WHERE in UPDATE statement
UPDATE table_name
SET column1 = value1
WHERE condition;
-- WHERE in DELETE statement
DELETE FROM table_name
WHERE condition;
Assume we have a table students with columns: name, age, and department.
-- Select students who are older than 18
SELECT name, age
FROM students
WHERE age > 18;
-- Select students from 'Engineering' department
SELECT name, department
FROM students
WHERE department = 'Engineering';
-- Select students whose age is between 20 and 25
SELECT name, age
FROM students
WHERE age BETWEEN 20 AND 25;
-- Select students who are not from 'Engineering' department
SELECT name, department
FROM students
WHERE department != 'Engineering';
age value is greater than 18.Always remember: if a row does not satisfy the WHERE condition, it will be excluded from the result set (or left unchanged in case of UPDATE/DELETE).
WHERE to narrow down queries to only relevant rows and improve performance.AND and OR, and use parentheses ( ) to control logic clearly.WHERE clause using a SELECT before running UPDATE or DELETE.BETWEEN both ends are included).NULL values correctly using IS NULL and IS NOT NULL instead of = NULL.AND/OR.SELECT query on a students table that returns students from the 'Science' department who are older than 19.BETWEEN to select employees whose salary is between 30,000 and 50,000.NOT (for example, students who are not in 1st year).IN to select rows where a department is one of several values (e.g., 'IT', 'CS', 'ECE').LIKE to filter students whose names start with the letter 'A'.