Getting the right rows is half the job; presenting them in the right order and in manageable pages is the other half. This chapter covers sorting by one or many keys, removing duplicates, and the pagination pattern behind every "page 2 of results".
ORDER BY
SELECT name, package FROM studentsORDER BY package DESC; -- highest first (ASC is default)-- Sort by several keys: programme A–Z, then package high→low within eachORDER BY programme ASC, package DESC;-- Sort by a computed expression or column positionORDER BY LENGTH(name);ORDER BY 2 DESC; -- the 2nd selected column
DISTINCT
SELECT DISTINCT programme FROM students; -- unique programmesSELECT DISTINCT programme, year FROM students; -- unique combinationsSELECT COUNT(DISTINCT programme) FROM students; -- how many distinct
LIMIT & pagination
LIMIT caps the number of rows; OFFSET skips rows — together they page through results:
SELECT * FROM students ORDER BY id LIMIT 10; -- first 10 (page 1)SELECT * FROM students ORDER BY id LIMIT 10 OFFSET 20; -- rows 21–30 (page 3)-- Top-N per querySELECT name, package FROM students ORDER BY package DESC LIMIT 5;-- (SQL Server uses TOP / OFFSET … FETCH; syntax varies by database.)
Sorting NULLs
Databases differ on where NULLs sort. Control it explicitly when it matters:
ORDER BY package DESC NULLS LAST; -- Postgres/Oracle-- Portable trick: sort by a flag firstORDER BY (package IS NULL), package DESC;
Practice
List the top 5 students by package. Get the distinct programmes. Build the query for "page 3" of a 10-per-page list ordered by enrolment date. Then sort by package descending with unknown packages pushed to the end.
Key takeaways
- 01ORDER BY sorts (ASC default); list several keys for tie-breaking; you can sort by expressions.
- 02DISTINCT returns unique rows/combinations; COUNT(DISTINCT col) counts them.
- 03LIMIT caps rows and OFFSET skips them — the pagination pattern.
- 04Always pair LIMIT/OFFSET with a stable ORDER BY or pages can repeat/skip rows.
- 05Control NULL sort position with NULLS LAST or a (col IS NULL) sort key.
