ORDER BY

 ORDER BY is used to sort the records based on the columns stored in a table.

        We can sort the records either in ascending order or descending order.

Note: By Default, it sorts the table in ascending order.

        Syntax:

                SELECT col1, col2, ... FROM table_name ORDER BY col_name (ASC/DESC);

        Example:

          Consider the following table:

            emp_id   emp_fname   emp_lname  dept         city           salary   

                   1           

Anup            

Mittal        

ME        

Delhi

60000

                   2

John

Doe

CSE

Bangalore

50000

                   3

Namita

Thankur

CSE

Delhi

55000

                   4

Aman

Singh

ME

UK

65000

                   5

Pratik

Thapar

CSE

Delhi

62000


          Let say you want to sort the data based on their salary:

                    SELECT * FROM Employee ORDER BY salary;
           Output: 
 emp_id   emp_fname   emp_lname  dept         city           salary       
2               John                Doe           CSE    Bangalore    

50000
3NamitaThankurCSEDelhi

55000
1AnupMittalMEUK

60000
5PratikThaparCSEDelhi

62000
4AmanSinghMEUK

65000

        Let say you want to show the same data in decreasing order of salary:

                    SELECT * FROM Employee ORDER BY salary DESC;
        Output:
 emp_id   emp_fname   emp_lname  dept         city           salary  
4                Aman            Singh        ME            UK

65000
5PratikThaparCSEDelhi

62000
1AnupMittalMEUK

60000
3NamitaThankurCSEDelhi

55000
2JohnDoeCSEBangalore

50000

        You can sort the table based on emp_fname or any valid column name.

Continue Learning: SQL Keys - Primary, Composite, Foreign, Alternate

            

Comments

Popular Posts