SQL Basics: Ask Questions of Data
Sorting, Limiting and Removing Duplicates
In this lesson you will
- Sort results ascending and descending with ORDER BY
- Return only some rows with LIMIT and OFFSET
- List unique values with DISTINCT
Introduction
A database does not promise to return rows in any particular order unless you ask. This lesson shows how to sort results, take the first few, and remove repeated values.
ORDER BY
ORDER BY sorts the result. The default is ascending (smallest first, or A to Z).
Add DESC for descending order, which gives the biggest first.
You can sort by more than one column. Rows that tie on the first column are sorted by the second.
Quick quiz
How do you list products from most expensive to cheapest?
WHERE and ORDER BY together
The order of the clauses matters: SELECT, FROM, WHERE, then ORDER BY.
LIMIT and OFFSET
LIMIT returns only the first rows. Together with ORDER BY it answers "top N" questions.
OFFSET skips rows first. This is how websites show "page 2" of results.
Always pair LIMIT with ORDER BY. Without sorting, "the first 3 rows" can be any 3.
DISTINCT
Several products share a category. DISTINCT returns each value once.
Look at where the NULL sorts. In SQLite, NULL counts as the smallest value, so it comes first in ascending order.
Quick quiz
What does SELECT DISTINCT category FROM products return?
Try it yourself
Show the two cheapest products that are in stock more than 50 times, with their name, price and stock.
Summary
ORDER BY columnsorts ascending.DESCreverses it. You can sort by several columns.LIMIT nkeeps the first n rows, andOFFSETskips rows first.DISTINCTremoves duplicate rows from the result.- Clause order is
SELECT,FROM,WHERE,ORDER BY,LIMIT.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading