The select statement in MySQL uses order to sort by row

  • 2020-12-21 18:12:50
  • OfStack

This article describes executing the select query statement in the MySQL database and sorting the results of the query using the order by clause.

Let's review the syntax of the select statement in SQL 1:

Basic syntax of Select statement:

Select < The set of columns > from < The name of the table > where < conditions > order by < Sort fields and ways >

If you want to sort the query results by a field, use the order by clause, as follows:

select * from < The name of the table > order by < The field names > < The sorting way >

Let's look at two examples. The first query queries all the data in the test table and sorts them in the positive order of t_id. The second query is the reverse of the first and is sorted in reverse order.

mysql > select t_id,t_name from test order by t_id;
+------+--------+
| t_id | t_name |
+------+--------+
| 1 | name1 |
| 2 | name2 |
+------+--------+
2 rows in set (0.00 sec)

mysql > select t_id,t_name from test order by t_id desc;
+------+--------+
| t_id | t_name |
+------+--------+
| 2 | name2 |
| 1 | name1 |
+------+--------+
2 rows in set (0.00 sec)

Note: When sorting in positive order, you can use asc as the sorting keyword or not. In reverse order, 1 always use desc as the keyword.

So much for this article about the use of order to sort by row in MySQL. I hope it will be helpful to you. Thank you!


Related articles: