Lesson 3 of 12 · 0 of 2 exercises solved

ORDER BY, LIMIT & DISTINCT

Rows in a table have no guaranteed order. ORDER BY sorts your results, LIMIT keeps only the first few, and DISTINCT removes duplicates.

-- Sort ascending (default):
SELECT name, grade FROM students ORDER BY grade;

-- Sort descending:
SELECT name, grade FROM students ORDER BY grade DESC;

-- Sort by several columns (ties broken by the next one):
SELECT name, age, grade FROM students
ORDER BY age DESC, grade DESC;

-- Only the first N rows:
SELECT name, grade FROM students
ORDER BY grade DESC
LIMIT 3;

-- Skip rows with OFFSET (page 2 of results):
SELECT name FROM students
ORDER BY name
LIMIT 10 OFFSET 10;
SQLite · sample databaseCtrl+Enter runs

DISTINCT removes duplicate rows from the result. Ask 'which ages appear in the table?' and you don't want 17 listed five times.

SELECT DISTINCT age FROM students;

-- DISTINCT applies to the whole selected row:
SELECT DISTINCT age, grade FROM students;
-- (only removes rows where BOTH values repeat)
SQLite · sample databaseCtrl+Enter runs

Practice

Return the name and grade of the three highest-graded students, best first.

Exercise

Top three

3 checks
SELECT name, grade FROM students;
 
SQLite · sample databaseCtrl+Enter runs
Output
Press Run to try your code, then Check answer to grade it.

each distinct age that appears in the students table, smallest first, as a single column called age.

Exercise

Distinct ages

2 checks
SELECT age FROM students;
 
SQLite · sample databaseCtrl+Enter runs
Output
Press Run to try your code, then Check answer to grade it.
Finished reading?2 exercises still open. You can come back to them later.

Tip: use the ← and → keys to move between lessons.