Filtering & Sorting Data
After this lesson, you will be able to:
- Use WHERE to filter rows based on conditions like =, !=, <, >, <=, >=
- Filter ranges with BETWEEN and match lists with IN
- Search text patterns using LIKE with % and _ wildcards (and know when to reach for full-text search instead)
- Combine multiple conditions with AND, OR, and NOT, and use parentheses to avoid 2 AM bugs
- Sort results with ORDER BY in ascending and descending order, including ties
- Combine WHERE, ORDER BY, and LIMIT in a single powerful query
- Handle NULL values correctly using IS NULL and IS NOT NULL (the #1 source of silent data bugs)
#WHERE — Your Data Filter
Filtering is where SQL gets powerful. In the last lesson, you got all the data from a table. Now you will learn to ask specific questions and get precise answers. This is like going from "show me the whole library" to "show me only mystery novels published after 2020."
WHERE clause filters rows based on a condition. Only rows that match the condition are returned:SELECT * FROM employees
WHERE department = 'Engineering';
This returns only employees in the Engineering department. The database checks every row: "Is this person's department Engineering?" If yes, include them. If no, skip them.
Try it! Run this query and then change 'Engineering' to 'Marketing' or 'Sales' to see different departments.
#Comparison Operators
SQL has six comparison operators for numbers, dates, and text:
| Operator | Meaning | Example |
|---|---|---|
= | Equal to | WHERE salary = 85000 |
!= or <> | Not equal to | WHERE department != 'Sales' |
> | Greater than | WHERE salary > 90000 |
< | Less than | WHERE salary < 80000 |
>= | Greater than or equal to | WHERE salary >= 90000 |
<= | Less than or equal to | WHERE salary <= 80000 |
#Filtering by Numbers
-- Employees earning more than 90K
SELECT name, salary FROM employees
WHERE salary > 90000;
-- Employees earning exactly 85K
SELECT name, salary FROM employees
WHERE salary = 85000;
-- Employees earning less than 80K
SELECT name, salary FROM employees
WHERE salary < 80000;
#Filtering by Text
Text comparisons use single quotes around the value:
-- Find all employees NOT in Marketing
SELECT name, department FROM employees
WHERE department != 'Marketing';
'like this' for text values, not double quotes. This is different from Python and JavaScript.#Filtering by Dates
YYYY-MM-DD format:-- Employees hired after 2021
SELECT name, hire_date FROM employees
WHERE hire_date > '2021-01-01';
-- Employees hired before 2020
SELECT name, hire_date FROM employees
WHERE hire_date < '2020-01-01';
Try it! Use the playground to find all employees with a salary greater than 85000.
What does SELECT name FROM employees WHERE salary >= 90000; return?
#BETWEEN — Range Filtering
salary >= 70000 AND salary <= 90000, you can use BETWEEN:-- Employees earning between 70K and 90K (inclusive)
SELECT name, salary FROM employees
WHERE salary BETWEEN 70000 AND 90000;
BETWEEN includes both endpoints. So BETWEEN 70000 AND 90000 means "70000, 90000, and everything in between."It works with dates too:
-- Employees hired in 2020
SELECT name, hire_date FROM employees
WHERE hire_date BETWEEN '2020-01-01' AND '2020-12-31';
#IN — Matching a List of Values
IN:-- Employees in specific departments
SELECT name, department FROM employees
WHERE department IN ('Engineering', 'Marketing');
-- Same result but more verbose:
-- WHERE department = 'Engineering' OR department = 'Marketing'
IN checks if a value matches ANY item in the list. It is cleaner and easier to read than chaining OR conditions, especially with long lists.-- Find orders for specific products
SELECT * FROM orders
WHERE product IN ('Widget A', 'Widget B', 'Widget C');
-- Find employees with specific IDs
SELECT * FROM employees
WHERE id IN (1, 3, 5, 7, 9);
#LIKE — Pattern Matching for Text
LIKE lets you use wildcards:| Wildcard | Meaning | Example |
|---|---|---|
% | Any sequence of characters (including none) | 'A%' matches "Alice", "Alex", "A" |
_ | Exactly one character | '_ob' matches "Bob", "Rob" |
-- Names starting with 'A'
SELECT name FROM employees
WHERE name LIKE 'A%';
-- Names ending with 'son'
SELECT name FROM employees
WHERE name LIKE '%son';
-- Names containing 'il'
SELECT name FROM employees
WHERE name LIKE '%il%';
-- Names with exactly 3 characters before 'Smith'
SELECT name FROM employees
WHERE name LIKE '___Smith';
Try it! Find all employees whose name starts with a letter between A and D.
#AND, OR, NOT — Combining Conditions
Real questions often need multiple conditions. SQL gives you three logical operators to combine them:
#AND — Both Conditions Must Be True
-- Engineers earning over 90K
SELECT name, department, salary FROM employees
WHERE department = 'Engineering'
AND salary > 90000;
Both conditions must be true for a row to appear. If someone is in Engineering but earns 85K, they are excluded. If someone earns 95K but is in Marketing, they are also excluded.
#OR — At Least One Condition Must Be True
-- Employees in Engineering OR Marketing
SELECT name, department FROM employees
WHERE department = 'Engineering'
OR department = 'Marketing';
A row appears if EITHER condition is true (or both).
#NOT — Reverses a Condition
-- Everyone NOT in Sales
SELECT name, department FROM employees
WHERE NOT department = 'Sales';
-- Same as:
-- WHERE department != 'Sales'
#Combining AND and OR (Use Parentheses!)
When mixing AND and OR, use parentheses to make the logic clear:
-- Engineers earning over 90K, OR anyone in Marketing
SELECT name, department, salary FROM employees
WHERE (department = 'Engineering' AND salary > 90000)
OR department = 'Marketing';
Without parentheses, SQL might interpret the logic differently than you expect. Always use parentheses when combining AND and OR.
Try it! Find employees who are in Engineering AND earn more than 90000.
#NULL — The Absence of Data
NULL. It means "unknown" or "not applicable."manager_id of NULL — meaning they have no manager (they are top-level).-- WRONG -- this does not work!
SELECT * FROM employees WHERE manager_id = NULL;
-- CORRECT -- use IS NULL
SELECT * FROM employees WHERE manager_id IS NULL;
-- Find employees who DO have a manager
SELECT * FROM employees WHERE manager_id IS NOT NULL;
What does WHERE manager_id IS NULL return?
#ORDER BY — Sorting Your Results
ORDER BY lets you sort:-- Sort by salary (lowest to highest -- ascending is the default)
SELECT name, salary FROM employees
ORDER BY salary;
-- Sort by salary (highest to lowest -- descending)
SELECT name, salary FROM employees
ORDER BY salary DESC;
-- Sort by department alphabetically, then by salary within each department
SELECT name, department, salary FROM employees
ORDER BY department, salary DESC;
ASC= ascending (A-Z, 0-9, earliest-latest). This is the default — you can omit itDESC= descending (Z-A, 9-0, latest-earliest). You must write it explicitly
#Sorting by Multiple Columns
When you sort by multiple columns, SQL sorts by the first column, then breaks ties with the second:
-- Sort by department (A-Z), then within each department, sort by salary (highest first)
SELECT name, department, salary FROM employees
ORDER BY department ASC, salary DESC;
This is like sorting a spreadsheet: first by one column, then by another to break ties.
Try it! Sort employees by salary from highest to lowest.
#Putting It All Together
The real power comes from combining WHERE, ORDER BY, and LIMIT in one query:
-- Top 3 highest-paid engineers
SELECT name, salary
FROM employees
WHERE department = 'Engineering'
ORDER BY salary DESC
LIMIT 3;
The order of clauses matters and must always follow this pattern:
SELECT columns
FROM table
WHERE conditions
ORDER BY column
LIMIT number;
Think of it as a pipeline:
- FROM. Start with the full table
- WHERE — filter down to matching rows
- ORDER BY — sort the remaining rows
- LIMIT. Take only the top N
Try it! Find the top 5 highest-paid employees who were hired after 2020.
#Practice Challenges
Use the playground below to tackle these challenges. Each one builds on what you have learned:
- Find all employees in the Sales department
- Find employees earning between 75000 and 90000
- Find employees whose name contains "son"
- Find engineers OR employees earning more than 90000
- Find the 3 most recently hired employees (sort by hire_date DESC)
- Find all orders with status 'completed', sorted by amount (highest first)
#Key Takeaways
- WHERE filters rows based on conditions using =, !=, >, <, >=, <= operators
- BETWEEN filters ranges inclusively —
BETWEEN 10 AND 20includes 10 and 20 - IN matches a list of values — cleaner than chaining multiple OR conditions (and the planner often rewrites OR chains into IN anyway)
- LIKE searches patterns with % (any characters) and _ (one character) wildcards — for fuzzy/full-text use Postgres'
pg_trgm,tsvector, or BigQuery'sSEARCH()instead - AND, OR, NOT combine conditions — always use parentheses when mixing AND and OR
- NULL is not a value — use IS NULL and IS NOT NULL, never = NULL. This bites every SQL engineer at least once
- ORDER BY sorts results — ASC (default) for ascending, DESC for descending. Add a tiebreaker column for deterministic output:
ORDER BY salary DESC, id ASC - Clause order is fixed: SELECT, FROM, WHERE, ORDER BY, LIMIT
Which query finds employees earning more than 80000 in the Marketing department?