SQL Tutorial menu

SQL ORDER BY

ORDER BY sorts the rows of a result, from smallest to largest or the other way round.

ORDER BY Syntax

Example

sql
SELECT column1, column2
FROM table_name
ORDER BY column1 ASC|DESC;
  • ASC means ascending: A to Z, 1 to 100. It is the default, so you can leave it out.
  • DESC means 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

sql
SELECT name, age
FROM students
ORDER BY age;
nameage
Hamza Raza18
Ali Khan19
Fatima Noor20
Ayesha Siddiqui21
Bilal Ahmed22
Sana Iqbal23

Sort Descending

To see the highest marks first, add DESC:

Example

sql
SELECT name, marks
FROM students
ORDER BY marks DESC;
namemarks
Fatima Noor92
Sana Iqbal88
Ayesha Siddiqui85
Ali Khan78
Hamza Raza70
Bilal Ahmed64

Sort Text Alphabetically

Text columns sort in alphabetical order:

Example

sql
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

sql
SELECT name, city, age
FROM students
ORDER BY city, age DESC;
namecityage
Fatima NoorIslamabad20
Bilal AhmedKarachi22
Ali KhanKarachi19
Hamza RazaKarachi18
Sana IqbalLahore23
Ayesha SiddiquiLahore21

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

sql
SELECT name, marks
FROM students
WHERE city = 'Karachi'
ORDER BY marks DESC;
namemarks
Ali Khan78
Hamza Raza70
Bilal Ahmed64

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

sql
SELECT name, marks
FROM students
ORDER BY marks DESC
LIMIT 3;
namemarks
Fatima Noor92
Sana Iqbal88
Ayesha Siddiqui85

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

OrderClause
1SELECT
2FROM
3WHERE
4ORDER BY
5LIMIT

Exercise

Exercise

Which query lists the courses from the longest to the shortest?

Learn SQL with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp