Tuesday, November 27

SQL- Order By



Order By
This is used to sort the result that is obtained, in ascending or descending order by using keyword Asc or Desc. It sorts the result-set by a specified column. By default it sorts in ascending order.

Syntax:
    " SELECT column_name(s)
      FROM table_name
      ORDER BY column_name(s) ASC | DESC "

Now see the examples below.
  •  " select FirstName, LastName from DimCustomer order by 
       FirstName  "
  •  " select FirstName, LastName from DimCustomer order by 
       FirstName asc "                                                                          
Both queries give same output, because by default order by clause sorts in ascending.

Result:


Order By Desc
This sorts the result-set in descending order, See the below query.

       " select FirstName, LastName from DimCustomer order by  
         FirstName desc "

Result:
Note: We can use where clause and order by clause with in same select statement depending on how we need result-set.