The SELECT query can grab data from a database table. This data is not ordered by a specific column, it’s just retrieved in the same way as the data was first inserted.

If you want to order the data, you can use the ORDER BY clause. You can order in two directions: ascending and descending. SQL needs to know what to sort the table on: a column name.

You may like:
Learning SQL: Master SQL Fundamentals

ORDER BY clause

Setup table

If you do not have a table with data, create it first. In this example we define a table named students with several columns: id, gender, firstname, lastname and student id.

The SQL query we use to do that is:

1
2
3
4
5
6
sql> CREATE DATABASE exampleDb;
sql> USE exampleDb;
sql> CREATE TABLE Students ( PersonID int, Gender int, LastName varchar(255), FirstName varchar(255), StudentIDint );
sql> INSERT INTO Students VALUES ( 13148, 0, 'Johnson', 'John', 6391931);
sql> INSERT INTO Students VALUES ( 13149, 1, 'Dylan', 'Abby', 439225);
sql> INSERT INTO Students VALUES ( 13149, 1, 'Hinton', 'Alice', 139225);

Syntax

Combine the SELECT query with the ORDER BY clause.

1
SELECT .. FROM table ORDER BY ... ASC 

Example

To order the results alphabetically on the first name, we can use:

1
2
3
4
5
6
7
8
sql> SELECT * FROM Students ORDER BY FirstName ASC;
+----------+----------+-----------+-----------+
| PersonID | LastName | FirstName | StudentID |
+----------+----------+-----------+-----------+
| 13149 | Dylan | Abby | 439225 |
| 13149 | Hinton | Alice | 139225 |
| 13148 | Johnson | John | 6391931 |
+----------+----------+-----------+-----------+

To do the same thing in reverse order:

1
2
3
4
5
6
7
8
sql> SELECT * FROM Students ORDER BY FirstName DESC;
+----------+----------+-----------+-----------+
| PersonID | LastName | FirstName | StudentID |
+----------+----------+-----------+-----------+
| 13148 | Johnson | John | 6391931 |
| 13149 | Hinton | Alice | 139225 |
| 13149 | Dylan | Abby | 439225 |
+----------+----------+-----------+-----------+

Video

Vide of ORDER BY below