SQL ORDER BY
ORDER BY sorts the rows of a result, from smallest to largest or the other way round.
ORDER BY Syntax
Example
SELECT column1, column2
FROM table_name
ORDER BY column1 ASC|DESC;ASCmeans ascending: A to Z, 1 to 100. It is the default, so you can leave it out.DESCmeans descending: Z to A, 100 to 1.
Without ORDER BY, the database may return rows in any order. If the order matters, always ask for it.
Sort Ascending
Example
SELECT name, age
FROM students
ORDER BY age;| name | age |
|---|---|
| Hamza Raza | 18 |
| Ali Khan | 19 |
| Fatima Noor | 20 |
| Ayesha Siddiqui | 21 |
| Bilal Ahmed | 22 |
| Sana Iqbal | 23 |
Sort Descending
To see the highest marks first, add DESC:
Example
SELECT name, marks
FROM students
ORDER BY marks DESC;| name | marks |
|---|---|
| Fatima Noor | 92 |
| Sana Iqbal | 88 |
| Ayesha Siddiqui | 85 |
| Ali Khan | 78 |
| Hamza Raza | 70 |
| Bilal Ahmed | 64 |
Sort Text Alphabetically
Text columns sort in alphabetical order:
Example
SELECT title
FROM courses
ORDER BY title;| title |
|---|
| Digital Marketing |
| Graphic Designing |
| Python Programming |
| Web Development |
Sort by Several Columns
You can give more than one column. The database sorts by the first column, and when two rows have the same value it uses the second column.
Example
SELECT name, city, age
FROM students
ORDER BY city, age DESC;| name | city | age |
|---|---|---|
| Fatima Noor | Islamabad | 20 |
| Bilal Ahmed | Karachi | 22 |
| Ali Khan | Karachi | 19 |
| Hamza Raza | Karachi | 18 |
| Sana Iqbal | Lahore | 23 |
| Ayesha Siddiqui | Lahore | 21 |
Cities are A to Z. Inside each city, the oldest student comes first.
ORDER BY with WHERE
WHERE comes before ORDER BY. First the rows are filtered, then sorted:
Example
SELECT name, marks
FROM students
WHERE city = 'Karachi'
ORDER BY marks DESC;| name | marks |
|---|---|
| Ali Khan | 78 |
| Hamza Raza | 70 |
| Bilal Ahmed | 64 |
Show Only the Top Rows
To get only the first few rows, MySQL, PostgreSQL and SQLite use LIMIT. Here are the top 3 students:
Example
SELECT name, marks
FROM students
ORDER BY marks DESC
LIMIT 3;| name | marks |
|---|---|
| Fatima Noor | 92 |
| Sana Iqbal | 88 |
| Ayesha Siddiqui | 85 |
SQL Server writes this as SELECT TOP 3 name, marks FROM students ORDER BY marks DESC;, and the official SQL standard uses FETCH FIRST 3 ROWS ONLY. The idea is the same.
Order of the Clauses
| Order | Clause |
|---|---|
| 1 | SELECT |
| 2 | FROM |
| 3 | WHERE |
| 4 | ORDER BY |
| 5 | LIMIT |
Exercise
Exercise
Which query lists the courses from the longest to the shortest?
