Chapter 7: Filtering and Sorting Advanced

Now we’re going to level up our WHERE clause and make our SELECT queries super powerful!

In the last chapter we learned basic filtering. Today we’ll master:

  • Combining conditions with AND, OR, NOT
  • Removing duplicates with DISTINCT
  • Advanced pattern matching with LIKE and wildcards (% and _)
  • Handling missing values properly with IS NULL and IS NOT NULL

Let’s make sure we have the same sample data in the students table. Run this once to reset and populate it nicely (copy-paste all at once):

SQL

Now let’s dive in!

1. Logical Operators: AND, OR, NOT

(How to combine multiple conditions)

Operator Meaning When to use
AND Both conditions must be true Narrow down results (strict filter)
OR At least one condition true Broaden results (any of these)
NOT Reverse the condition Exclude something

Important rule: Use parentheses () when mixing AND and OR — otherwise MySQL follows AND first, then OR (like multiplication before addition).

Examples – Try these!

A. Active female students who joined in 2025

SQL

B. Students who are either male OR joined after February 2025

SQL

C. Active students who are NOT male (i.e., female or other)

SQL

D. Careful with AND + OR – Use parentheses! Wrong (MySQL will read AND first):

SQL

Correct way:

SQL

2. DISTINCT Keyword – Remove Duplicate Rows

Syntax:

SQL

Example – Get unique genders and join years

SQL

Multiple columns:

SQL

3. Pattern Matching with LIKE and Wildcards (% and _)

LIKE is used for text pattern matching.

Wildcard Meaning Example
% Zero or more characters (anything) ‘Priya%’ → starts with Priya
_ Exactly one character ‘P_iya’ → P + any char + iya

Examples:

A. Names starting with ‘P’ or ‘R’

SQL

B. Names ending with ‘a’

SQL

C. Names containing ‘Sh’ anywhere

SQL

D. Emails ending with @gmail.com

SQL

E. Phone numbers starting with 98 and exactly 10 digits (using _ )

SQL

4. NULL Handling – IS NULL and IS NOT NULL

(NEVER use = NULL or != NULL – it won’t work!)

NULL means “value is missing / unknown”.

Correct way:

What you want Correct Syntax Wrong (does NOT work)
Phone is missing phone IS NULL phone = NULL
Phone exists phone IS NOT NULL phone != NULL

Examples:

A. Students who have NOT provided phone number

SQL

B. Students who HAVE provided phone number

SQL

C. Students who have notes (notes is NOT NULL)

SQL

That’s it for Chapter 7! 🎉 You can now write very smart, precise queries that answer almost any business question!

Homework for today (do it right now – super important!) Run these 4 queries and paste the output of each here:

SQL

You may also like...

Leave a Reply

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