SQL ORDER BY Clause

The SQL ORDER BY clause is used to sort the record in ascending or descending order, based on columns.
The ORDER BY clause sorts the records in ascending order by default.
To sort the records in descending order, use the DESC keyword
To sort the records in ascending order, use the ASC keyword.

The basic syntax of the ORDER BY clause is as follows −

SELECT [column-name] FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]

Consider the tbl_student_record table having the following records

id name class subject city phone fee fee_date
1 Mohan 2nd Math Agra 999999990 500 2018-01-02
2 Pooja 3rd English Delhi 999999991 200 2018-01-11
3 Rahul 4th Math Agra 999999992 300 2018-01-05
4 Suresh 2nd English Agra 999999993 400 2018-01-22
5 Vivek 3rd Math Agra 999999994 500 2018-01-01
6 Anuj 2nd English Delhi 999999995 600 2018-01-31
7 Sanju 4th Math Agra 999999996 400 2018-01-17
8 Rohit 3rd English Delhi 999999997 700 2018-01-10
9 Mahesh 3rd Math Agra 999999998 800 2018-01-24
10 Munesh 4th English Delhi 999999999 200 2018-01-09

The following Query has an example, which would sort the result in an ascending order by the NAME

SELECT * FROM tbl_student_record ORDER BY name ASC

Output

id name class subject city phone fee fee_date
6 Anuj 2nd English Delhi 999999995 600 2018-01-31
9 Mahesh 3rd Math Agra 999999998 800 2018-01-24
1 Mohan 2nd Math Agra 999999990 500 2018-01-02
10 Munesh 4th English Delhi 999999999 200 2018-01-09
2 Pooja 3rd English Delhi 999999991 200 2018-01-11
3 Rahul 4th Math Agra 999999992 300 2018-01-05
8 Rohit 3rd English Delhi 999999997 700 2018-01-10
7 Sanju 4th Math Agra 999999996 400 2018-01-17
4 Suresh 2nd English Agra 999999993 400 2018-01-22
5 Vivek 3rd Math Agra 999999994 500 2018-01-01

The following Query has an example, which would sort the result in an descending order by the NAME -

SELECT * FROM tbl_student_record ORDER BY name DESC 

Output

id name class subject city phone fee fee_date
5 Vivek 3rd Math Agra 1E+09 500 2018-01-01
4 Suresh 2nd English Agra 1E+09 400 2018-01-22
7 Sanju 4th Math Agra 1E+09 400 2018-01-17
8 Rohit 3rd English Delhi 1E+09 700 2018-01-10
3 Rahul 4th Math Agra 1E+09 300 2018-01-05
2 Pooja 3rd English Delhi 1E+09 200 2018-01-11
10 Munesh 4th English Delhi 1E+09 200 2018-01-09
1 Mohan 2nd Math Agra 1E+09 500 2018-01-02
9 Mahesh 3rd Math Agra 1E+09 800 2018-01-24
6 Anuj 2nd English Delhi 1E+09 600 2018-01-31

To Learn more in Hindi Language watch this Video.

order by clause in MySQL with example

If love this tutorial Please Like this page