Module 4 Filtering with the WHERE Clause (Equal & Not Equal)

Module 4

Filtering with the WHERE Clause (Equal & Not Equal)

A step-by-step, hands-on SQL practice lesson

SELECT * FROM employees WHERE department = 'Sales';

So far you've learned to pull entire tables, choose specific columns, and rename them with aliases. But real queries almost always need to answer a narrower question — like "show me only the Sales team" or "everyone except the interns." That's exactly what the WHERE clause does. In this lesson, you'll learn to filter rows using the two most common comparisons: equal (=) and not equal (!= or <>).

Introduction

What You'll Learn — and Why It Matters

🎯 Objective

By the end of this lesson, you will be able to:

  • Filter query results to only the rows that match a condition, using WHERE.
  • Use = to match an exact value, and != or <> to exclude one.
  • Correctly quote text values versus numeric values inside a condition.
  • Understand why WHERE can't see column aliases from the same query.

⚠️ What to Avoid

Common mistakes
  • Forgetting to put quotes around text values, like WHERE department = Sales instead of WHERE department = 'Sales'.
  • Using = NULL or != NULL to check for missing values — this silently returns the wrong results (explained below).
  • Assuming an alias created in SELECT can be reused inside the same query's WHERE — it can't (a rule you may recognize from Module 2).

💡 Important to Know

Before you start

WHERE filters rows, not columns — it decides which records make it into your results, after you've already chosen which columns to show. In MySQL, != and <> do exactly the same thing; which one you use is just a style preference.

Requirements

What You'll Need Before Starting

Operating SystemWindows, macOS, or Linux — this lesson works identically on all of them.
Database ServerMySQL installed and running. See How to Install MySQL if you haven't set it up yet.
Optional but recommendedXAMPP with phpMyAdmin, for a visual way to run queries. See How to Install XAMPP.
Prior knowledgeComfortable with SELECT column FROM table; and aliases from Module 1.

Practice

Step-by-Step Practice

Follow along in order — each step builds on the one before it.

1 Open MySQL (CLI or phpMyAdmin)

Open a terminal and connect with the MySQL command-line client, or open phpMyAdmin in your browser at http://localhost/phpmyadmin/.

mysql -u root -p

The basic syntax pattern for this lesson looks like this:

SELECT column1, column2 FROM table_name WHERE condition;

2 Create a Database and Verify It

Create a fresh practice database and confirm it exists before moving on.

CREATE DATABASE module4_practice;
SHOW DATABASES;
USE module4_practice;

Now create a table and verify it was created:

CREATE TABLE employees (
  id INT PRIMARY KEY,
  name VARCHAR(50),
  department VARCHAR(50),
  salary INT,
  status VARCHAR(20)
);
SHOW TABLES;
DESCRIBE employees;

3 Insert Sample Data

Add a few rows across different departments so filtering actually shows a difference.

INSERT INTO employees (id, name, department, salary, status) VALUES
(1, 'Sokha', 'Sales', 2800, 'Active'),
(2, 'Maria', 'Marketing', 3200, 'Active'),
(3, 'Wei', 'Sales', 3000, 'Inactive'),
(4, 'Aiden', 'IT', 3500, 'Active'),
(5, 'Nadia', 'HR', 2600, 'Active');

4 Filter with Equal (=)

Return only rows where department exactly matches 'Sales'.

SELECT * FROM employees WHERE department = 'Sales';

5 Filter with Not Equal (!=)

Return every row except Sales.

SELECT * FROM employees WHERE department != 'Sales';

6 Filter with Not Equal (<>)

MySQL's alternate "not equal" symbol — it does exactly the same thing as !=.

SELECT * FROM employees WHERE department <> 'Sales';

7 Filter a Numeric Column

Equality works the same way on numbers — just skip the quotes.

SELECT name, salary FROM employees WHERE salary = 3000;

8 Combine WHERE with Column Selection and an Alias

Bring together what you learned in Module 2 with today's filtering.

SELECT name AS employee_name, department
FROM employees
WHERE status = 'Active';

9 See Why NULL Needs Special Handling

Add a row with a missing department, then compare the two approaches.

INSERT INTO employees (id, name, department, salary, status) VALUES (6, 'Liam', NULL, 2900, 'Active');

-- This returns NOTHING, even though the row exists:
SELECT * FROM employees WHERE department = NULL;

-- This is the correct way to find it:
SELECT * FROM employees WHERE department IS NULL;

Troubleshooting

Common Problems and Solutions

Problem 1: Query returns zero rows, even though the data is clearly there

You ran WHERE department = Sales (no quotes) and got an error, or a query with extra spaces returned nothing.

SolutionAlways wrap text values in quotes — WHERE department = 'Sales'. If it still returns nothing, check for hidden trailing spaces in your data using WHERE department = 'Sales ' or trim the column when inserting data.

Problem 2: "WHERE column = NULL" doesn't find NULL rows

You expected this to match empty/missing values, but it always returns zero rows.

SolutionNULL means "unknown," so SQL can never say it's "equal" to anything — not even another NULL. Use IS NULL or IS NOT NULL instead of = or !=.

Problem 3: Trying to match multiple values with a single =

Writing something like WHERE department = 'Sales' AND 'HR' throws an error or returns unexpected results.

Solution= only compares to one value at a time. To match either department, use WHERE department = 'Sales' OR department = 'HR' — or the shorter IN ('Sales', 'HR'), which we'll cover in a future module.

Problem 4: An alias from SELECT isn't recognized inside WHERE

You aliased name AS employee_name and then tried WHERE employee_name = 'Sokha', and got an "unknown column" error.

SolutionThis is the same rule from Module 2: WHERE is evaluated before column aliases exist. Filter using the real column name — WHERE name = 'Sokha' — and keep the alias for display only.

Conclusion

What You Should Take Away

You should now be comfortable narrowing your results down to exactly the rows you need, using = to match a value and != or <> to exclude one — and you know why NULL needs its own special handling instead of a normal equality check.

In Module 5, we'll build on this by adding comparison operators like >, <, >=, and <=, plus combining multiple conditions with AND and OR.

Homework

Homework & Quiz

📝 Homework Task

Using the employees table from this lesson, write your own query that:

  • Selects name and salary only.
  • Filters for employees where status is not equal to 'Inactive'.
  • Renames salary to "Monthly Pay" using an alias.

Try writing it yourself before checking — there's no single "correct" answer as long as the logic matches these three requirements.

🧪 Quiz: Test Your Understanding (10 Questions)

Answer all 10, then click Submit to see your score instantly.

1. Which operator checks for an exact match in SQL?

2. Which two operators both mean "not equal" in MySQL?

3. True or False: WHERE filters columns, not rows.

4. What does WHERE department = NULL return?

5. Which is the correct way to filter a text column?

6. In query execution order, which runs first?

7. SELECT * FROM employees WHERE department <> 'HR'; returns:

8. To correctly check for missing (NULL) values, you should use:

9. WHERE salary = 3000 — do you need quotes around 3000?

10. Which clause would you add to also sort the filtered results?

0 / 10

FAQ

Frequently Asked Questions

1. What's the difference between = and != in SQL?

= matches rows where the column exactly equals a value. != (or <>) does the opposite — it matches every row where the column does NOT equal that value.

2. Are != and <> really the same thing in MySQL?

Yes, completely interchangeable in MySQL. != is more common in general programming; <> is the standard SQL symbol you'll see in older textbooks and other database systems.

3. Is SQL text comparison case-sensitive?

By default in MySQL, text comparisons are usually case-insensitive (depending on the column's collation setting), so 'sales' and 'Sales' often match the same rows. This can vary by database configuration.

4. Can I use WHERE with a column that has an alias?

Not the alias from the same SELECT — WHERE only sees the real, underlying column names. You can alias the column for display purposes after filtering with its real name.

5. Why does WHERE column = NULL never work?

In SQL, NULL means "unknown" rather than empty or zero, so nothing — not even another NULL — is ever considered "equal" to it. Always use IS NULL or IS NOT NULL for these checks.

6. Do I need quotes around numbers in WHERE?

No. Quotes are only for text (string) values. Numeric comparisons like WHERE salary = 3000 should be written without quotes.

7. Can WHERE filter more than one condition at once?

Yes, using AND and OR to combine multiple conditions — we'll cover that in detail in an upcoming module.

8. What happens if my WHERE condition matches zero rows?

MySQL simply returns an empty result set — no error, just zero rows. This is normal and expected when nothing in the table matches your filter.

9. Does the order of columns in WHERE matter?

No. WHERE department = 'Sales' AND status = 'Active' works exactly the same regardless of which condition you write first.

10. Can I filter using a column that isn't in my SELECT list?

Yes. WHERE can reference any real column in the table, whether or not you're displaying it in your results.

11. What's the difference between WHERE and HAVING?

WHERE filters individual rows before any grouping happens. HAVING filters after rows have been grouped with GROUP BY — a topic covered in a later module.

12. Is there a shortcut for matching several possible values at once?

Yes — the IN operator, for example WHERE department IN ('Sales', 'HR'), is a cleaner alternative to chaining several OR conditions. We'll cover it soon.

Post a Comment

Previous Post Next Post