Filtering and Sorting
💻 SQLUse WHERE, comparison operators, LIKE, IN and ORDER BY to find exactly the rows you need.
Most of the time you do not want the whole table. Filtering narrows rows; sorting decides the order they come back in.
- Filter with WHERE.
- Combine conditions with AND and OR.
- Search text with LIKE.
- Sort with ORDER BY.
WHERE
Use comparison operators to keep matching rows. String values go in single quotes; numbers do not.
SELECT name, score
FROM students
WHERE score >= 70;Combining Conditions
Use AND when both conditions must hold, OR when either may. Parentheses make the intention clear.
SELECT name, level, score
FROM students
WHERE level = 'SS2'
AND (score >= 70 OR score IS NULL);Pattern Matching
LIKE matches text. % means any number of characters and _ means exactly one.
SELECT name
FROM students
WHERE name LIKE 'A%';
SELECT name
FROM students
WHERE name LIKE '%olu%';Sorting
ORDER BY sorts ascending by default. Use DESC for highest first and add a second column as a tie-breaker.
SELECT name, score
FROM students
ORDER BY score DESC, name ASC;Practice
- Find students in SS1 with a score above 60.
- List names starting with B.
- Sort students by level, then by name.
Hands-on exercise
Write a query that returns name and score from students where:
1. score is at least 50.
2. level is either SS2 or SS3.
Sort by score from highest to lowest.
Recap
WHERE chooses rows, LIKE searches text and ORDER BY arranges the result. Use IS NULL for missing values.
Example
SELECT name, score
FROM students
WHERE score >= 70;
Exercises
1. score is at least 50.
2. level is either SS2 or SS3.
Sort by score from highest to lowest.
Expected Output
Only SS2/SS3 students with 50 or more, highest score first.
Lesson Nav
SQL Course
0/9 lessons completed
- 1 What a Database Is Tutorial
- 2 Filtering and Sorting Tutorial
- 3 Aggregates and Grouping Tutorial
- 4 Joining Tables Tutorial
- 5 Subqueries and Common Table Expressions Tutorial
- 6 Inserting, Updating and Deleting Tutorial
- 7 Schemas, Keys and Normalisation Tutorial
- 8 Indexes and Query Performance Tutorial
- 9 Project: A Reporting Query Project