Filtering data in SQL

Filtering data in SQL is done mainly with the WHERE clause (and sometimes HAVING for aggregated results). It allows you to extract only the rows that meet certain conditions.

Here’s a breakdown of the most common filtering techniques:


🔹 1. Basic Filtering with WHERE

SELECT *
FROM employees
WHERE department = 'Sales';

✅ Returns only employees in the Sales department.


🔹 2. Comparison Operators

  • = : equal
  • != or <> : not equal
  • <, >, <=, >=
SELECT *
FROM employees
WHERE salary > 50000;

🔹 3. Filtering with AND / OR / NOT

SELECT *
FROM employees
WHERE department = 'Sales' AND salary > 50000;

SELECT *
FROM employees
WHERE department = 'Sales' OR department = 'Marketing';

SELECT *
FROM employees
WHERE NOT department = 'HR';

🔹 4. Range Filtering: BETWEEN

SELECT *
FROM employees
WHERE salary BETWEEN 40000 AND 60000;

🔹 5. Matching Multiple Values: IN

SELECT *
FROM employees
WHERE department IN ('Sales', 'Marketing', 'HR');

🔹 6. Pattern Matching: LIKE

  • % = any number of characters
  • _ = single character
SELECT *
FROM employees
WHERE name LIKE 'J%';    -- names starting with J

SELECT *
FROM employees
WHERE name LIKE '%son';  -- names ending with "son"

🔹 7. Filtering NULL Values

SELECT *
FROM employees
WHERE manager_id IS NULL;     -- no manager assigned

🔹 8. Filtering After Aggregation: HAVING

HAVING is used with GROUP BY, because WHERE cannot filter aggregated results.

SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;

Leave a Reply