Sort MySQL
We know that to read the data using SQL SELECT statement from the MySQL table.
If we need to sort of read data, we can use the MySQL ORDER BY clause according to which you want to set a field which way to sort, and then returned in the search results.
grammar
The following is a SQL SELECT statement ORDER BY clause to sort query data and then return the data:
SELECT field1, field2,...fieldN FROM table_name1, table_name2... ORDER BY field1 [ASC [DESC][默认 ASC]], [field2...] [ASC [DESC][默认 ASC]]
- You can use any sort of field as a condition, to return query results sorted.
- You can set multiple fields to sort.
- You can use the ASC or DESC keyword to set the query results in ascending or descending order. By default, it is ascending.
- You can add WHERE ... LIKE clause to set conditions.
At the command prompt using the ORDER BY clause
The following will use the ORDER BY clause in the SQL SELECT statement to read data in MySQL data tables runoob_tbl:
Examples
Try following examples, the results are ordered in ascending and descending order.
SQL Sorting
mysql
>
use
RUNOOB
;
Database
changed
mysql
>
SELECT
*
from
runoob_tbl
ORDER
BY
submission_date
ASC
; +-----------+---------------+---------------+-----------------+ |
runoob_id
|
runoob_title
|
runoob_author
|
submission_date
| +-----------+---------------+---------------+-----------------+ |
3
| 学习
Java
|
RUNOOB
.
COM
|
2015
-
05
-
01
| |
4
| Learning
Python
|
RUNOOB
.
COM
|
2016
-
03
-
06
| |
1
| Learning
PHP
| rookie Tutorial |
2017
-
04
-
12
| |
2
| Learning
MySQL
| rookie Tutorial |
2017
-
04
-
12
| + ----- --------------- + --------------- + ------ + ----------- + ------
. 4
rows
in
SET
(
0.01
sec
)
MySQL
>
the SELECT
*
from
runoob_tbl
the ORDER
BY
submission_date
DESC
; + ----------- + --------------- + --------------- + - + ---------------- |
runoob_id
|
runoob_title
|
runoob_author
|
submission_date
| + ----------- + ----------- + ----------------- + --------------- + ---- |
1
| learning
PHP
| rookie tutorial |
2017
-
04
-
12
| |
2
| learning
MySQL
| rookie tutorial |
2017
-
04
-
12
| |
4
| learning
Python
|
RUNOOB
.
COM
|
2016
-
03
-
06
| |
3
| Learning
the Java
|
RUNOOB
.
COM
|
2015
-
05
-
01
| + ----------- + + --------------- ----------------- + + ---------------
. 4
rows
in
SET
(
0.01
sec
)
Runoob_tbl read all the data in the table in ascending order in accordance submission_date field.