In this article we will see "How to use ORDER BY in MySql" to sort the result-set in ascending or descending order and "ORDER BY query syntax with example".

ORDER BY query in MySql syntax

The ORDER BY statement is used to sort the result-set in ascending or descending order, syntax is as follows.


SELECT column1, column2, ...
FROM tableName
ORDER BY column1, column2, ... ASC|DESC;


ORDER BY query in MySql example

The ORDER BY statement is used to sort the result-set in ascending or descending order, as shown below:


/*Example EMPLOYEE table */
+----+--------+---------+
| id | name   | email   |
+----+--------+---------+
|  1 | name-1 | email-1 |
|  2 | name-2 | email-2 |
|  3 | name-3 | email-3 |
|  4 | name-4 | email-4 |
|  5 | name-1 | email-5 |
|  6 | name-2 | email-6 |
+----+--------+---------+



We will now apply ORDER BY on above table to sort the result-set in ascending or descending order of 'name' column:


/* By default values are sorted in ascending order*/
SELECT * FROM EMPLOYEE ORDER BY NAME;

/* DESC is used to sort values in descending order*/
SELECT * FROM EMPLOYEE ORDER BY NAME DESC;

Output: Output will be something like this:


/* Result for : SELECT * FROM EMPLOYEE ORDER BY NAME;*/
+----+--------+---------+
| id | name   | email   |
+----+--------+---------+
|  1 | name-1 | email-1 |
|  5 | name-1 | email-5 |
|  2 | name-2 | email-2 |
|  6 | name-2 | email-6 |
|  3 | name-3 | email-3 |
|  4 | name-4 | email-4 |
+----+--------+---------+

/* Result for : SELECT * FROM EMPLOYEE ORDER BY NAME DESC;*/
+----+--------+---------+
| id | name   | email   |
+----+--------+---------+
|  4 | name-4 | email-4 |
|  3 | name-3 | email-3 |
|  2 | name-2 | email-2 |
|  6 | name-2 | email-6 |
|  1 | name-1 | email-1 |
|  5 | name-1 | email-5 |
+----+--------+---------+



In this article we have seen "How to use ORDER BY in MySql" and "ORDER BY query syntax with example", in upcoming articles we will see more about Mysql syntax and queries with example.
  • By Techburps.com
  • Oct 20, 2017
  • MySql