EN
MySQL - ORDER BY clause
0 points
In this article, we would like to show you how to use ORDER BY
clause in MySQL.
Quick solution:
xxxxxxxxxx
1
SELECT `column1`, `column2`, ...
2
FROM `table_name`
3
ORDER BY `column1`, `column2`, ... ASC|DESC;
To show how the ORDER BY
clause works, we will use the following table:

Note:
At the end of this article you can find database preparation SQL queries.
In this example, we will sort users data by name.
Note:
By default
ORDER BY
clause sorts the data in ascending order.
Query:
xxxxxxxxxx
1
SELECT * FROM `users` ORDER BY `name`;
Output:

In this example, we will sort users data by name in descending order.
Query:
xxxxxxxxxx
1
SELECT * FROM `users` ORDER BY `name` DESC;
Output:

create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE `users` (
2
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
3
`name` VARCHAR(100) NOT NULL,
4
`role` VARCHAR(15) NOT NULL,
5
PRIMARY KEY (`id`)
6
)
7
ENGINE=InnoDB;
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO `users`
2
(`name`, `role`)
3
VALUES
4
('John', 'admin'),
5
('Chris', 'moderator'),
6
('Kate', 'user'),
7
('Denis', 'moderator');