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:
Eliminating duplicate rows
Sorting data in a meaningful order
Returning just a portion of the results
These techniques are essential when working with large tables and improve both readability and performance.
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.
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
ASC
sorts in ascending (A–Z or smallest to largest) order — this is the default
DESC
sorts in descending (Z–A or largest to smallest) order
You can sort by multiple columns by separating them with commas.
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;
LIMIT
specifies the number of rows to return
OFFSET
skips a number of rows before starting to return data
This is especially useful for creating pagination features like “page 1”, “page 2”, etc.
Use DISTINCT
to remove duplicate rows and return only unique values.
Use ORDER BY
to sort results alphabetically or numerically, in ascending or descending order.
Use LIMIT
and OFFSET
to return only a portion of the results — great for previews or pagination.
Combining these clauses helps refine your data retrieval for clarity and performance.
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:
Return a list of unique values from a column
Sort rows by text and numerical fields
Fetch the top or bottom results in a list
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!