Skip to main content
Albero Academy

Sorting, Limiting & Pagination

Order results precisely, remove duplicates with DISTINCT, and page through large result sets with LIMIT and OFFSET.

Chapter 7SQL13 min readBeginner friendly
  • #SQL
  • #ORDER BY
  • #Pagination

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

sorting
SELECT name, package FROM students
ORDER BY package DESC; -- highest first (ASC is default)
-- Sort by several keys: programme A–Z, then package high→low within each
ORDER BY programme ASC, package DESC;
-- Sort by a computed expression or column position
ORDER BY LENGTH(name);
ORDER BY 2 DESC; -- the 2nd selected column

DISTINCT

unique rows
SELECT DISTINCT programme FROM students; -- unique programmes
SELECT DISTINCT programme, year FROM students; -- unique combinations
SELECT COUNT(DISTINCT programme) FROM students; -- how many distinct

LIMIT & pagination

LIMIT caps the number of rows; OFFSET skips rows — together they page through results:

paging 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 query
SELECT 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:

NULL ordering
ORDER BY package DESC NULLS LAST; -- Postgres/Oracle
-- Portable trick: sort by a flag first
ORDER 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

  1. 01ORDER BY sorts (ASC default); list several keys for tie-breaking; you can sort by expressions.
  2. 02DISTINCT returns unique rows/combinations; COUNT(DISTINCT col) counts them.
  3. 03LIMIT caps rows and OFFSET skips them — the pagination pattern.
  4. 04Always pair LIMIT/OFFSET with a stable ORDER BY or pages can repeat/skip rows.
  5. 05Control NULL sort position with NULLS LAST or a (col IS NULL) sort key.