Don't Afraid of Source Code

MySQL Order By

0

The data return by a SELECT query can be sorted into a specified order using ORDER BY clause.

Syntax:

SELECT column-name FROM table-name ORDER BY column-name;

When the ORDER BY keywords are followed by a table column name the retrieved data will be sorted into order based upon the type of data in the specified column. Typically, if the column data type is numerical, the retrieved data will be sorted in ascending numerical order. If the column data type is textual the retrieved data will be sorted into alphabetical order from A to Z.

Ex: MySQL Table tblemployee

id Emp_Name Emp_Code Emp_Email
1 Anuj Kumar 10806121 phpgurukulofficial@gmail.com
2 Sanjeev Kumar 1908763 sanjv @test.com
3 Jonh Doe 10899781 jonhdie@abc.com
SELECT  *  FROM  tblemployee ORDER BY id;

Output:

id Emp_Name Emp_Code Emp_Email
1 Anuj Kumar 10806121 phpgurukulofficial@gmail.com
2 Sanjeev Kumar 1908763 sanjv @test.com
3 Jonh Doe 10899781 jonhdie@abc.com
SELECT  *  FROM  tblemployee ORDER BY Emp_Name;

Output:

id Emp_Name Emp_Code Emp_Email
1 Anuj Kumar 10806121 phpgurukulofficial@gmail.com
3 Jonh Doe 10899781 jonhdie@abc.com
2 Sanjeev Kumar 1908763 sanjv @test.com

For viewing data in descending sorted order the word DESC must be mentioned after the column name and before the semi colon in the ORDER BY clause. In case there is no mention of the sort order, data will be sorted in ascending order by default.

Syntax:

SELECT * FROM table_name ORDER BY column-name SORT ORDER;

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Privacy & Cookies Policy