ORDER BY & SELECT TOP / LIMIT
ORDER BY sorts rows. ASC means ascending (A→Z, small→large). DESC means descending. Default is ASC if you omit it.
ORDER BY — sort results
ORDER BY sorts rows. ASC means ascending (A→Z, small→large). DESC means descending. Default is ASC if you omit it.
You can sort by multiple columns: first by grade_level, then by full_name inside each grade.
Real-life example: ORDER BY is like sorting exam papers — first by class, then by roll number inside each class.
SELECT full_name, grade_level, city
FROM students
ORDER BY grade_level ASC, full_name ASC;
SELECT full_name, grade_level
FROM students
ORDER BY grade_level DESC;SELECT TOP / LIMIT — only first N rows
Sometimes you only want a few rows — top 5 scores or first 10 students alphabetically. SQL Server and MS Access use SELECT TOP n. MySQL, PostgreSQL, and SQLite use LIMIT n at the end.
Combine ORDER BY with TOP or LIMIT to get 'highest' or 'lowest' rows, not random ones.
Real-life example: TOP/LIMIT is like reading only the first page of search results instead of all 10,000 matches.
-- SQL Server / Access
SELECT TOP 5 full_name, grade_level
FROM students
ORDER BY full_name;-- MySQL, PostgreSQL, SQLite
SELECT full_name, grade_level
FROM students
ORDER BY full_name
LIMIT 5;
-- Skip first 5, take next 5 (pagination)
SELECT full_name, grade_level
FROM students
ORDER BY full_name
LIMIT 5 OFFSET 5;