New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› SQL› Filtering and Sorting

Filtering and Sorting

💻 SQL

Use WHERE, comparison operators, LIKE, IN and ORDER BY to find exactly the rows you need.

Lesson 2 of 9 Tutorial
0 of 9 completed

Most of the time you do not want the whole table. Filtering narrows rows; sorting decides the order they come back in.

By the end of this lesson you can:
  • 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;
Warning NULL is not equal to anything, not even NULL. Use IS NULL or IS NOT NULL instead of = NULL.

Practice

  1. Find students in SS1 with a score above 60.
  2. List names starting with B.
  3. 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

Exercise 1. Filter the top students Easy
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.
SQL exercise-1.sql
Expected Output
Only SS2/SS3 students with 50 or more, highest score first.

Lesson Nav

Lesson sections