SQL Lesson 3: Filtering and Sorting Query Results

April 22, 2025 | Categories: Information

In previous lessons, we learned how to retrieve data from a database using the SELECT statement and apply conditions using WHERE. Now, let’s dive into more ways to refine your query results by:

These techniques are essential when working with large tables and improve both readability and performance.

🔁 Removing Duplicate Results with DISTINCT

Even if your table has unique rows, your query results might contain duplicates—especially when selecting values from a single column. The DISTINCT keyword helps remove repeated values and return only unique entries.

Basic format:

SELECT DISTINCT column_name
FROM table_name;

This tells SQL to return each value of column_name only once. If multiple columns are selected, DISTINCT will keep unique combinations of those columns. We’ll look at more powerful grouping techniques using GROUP BY in an upcoming lesson.

🔤 Sorting Results with ORDER BY

Real-life databases are rarely ordered in a meaningful way. If we want our query results to be easier to read and interpret, we can sort them using the ORDER BY clause.

Basic format:

SELECT column1, column2
FROM table_name
ORDER BY column1 ASC;  -- or DESC

You can sort by multiple columns by separating them with commas.

🔢 Limiting Results with LIMIT and OFFSET

When working with large result sets, you might want to see just a small portion — for instance, the top 5 rows or the next 10 records after skipping some. This is where LIMIT and OFFSET come in handy.

Basic format:

SELECT column1
FROM table_name
ORDER BY column1
LIMIT number_rows OFFSET skip_rows;

This is especially useful for creating pagination features like “page 1”, “page 2”, etc.


✅ Key Takeaways


📝 Exercise Overview

In this lesson’s practice section, you’ll build SQL queries that use DISTINCT, ORDER BY, LIMIT, and OFFSET to control the shape and order of your result sets.

You’ll explore how to:

Each exercise is based on the oscar_movies table, and designed to help you become more confident in shaping your query output to fit your needs. You won’t just retrieve rows — you’ll shape, sort, and streamline them!

Leave a comment:

Comments: