Saturday, March 1, 2014

ORDER BY Clause in SQL


ORDER BY keyword:-

The SQL ORDER BY clause is used to sort the records in the result set for a SELECT statement.

The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword.


ASC is optional. It sorts the result set in ascending order by expression (default, if no modifier is provider).

DESC is optional. It sorts the result set in descending order by expression.


NOTE:-
If the ASC or DESC modifier is not provided in the ORDER BY clause, the results will be sorted by expression in ascending order (which is equivalent to "ORDER BY expression ASC").

Example:- Sorting without using  ASC/DESC keyword

    select po_header_id, creation_date
    from po_headers_all
    order by creation_date;

   
Example:- Sorting using ASC keyword

    select po_header_id, creation_date
    from po_headers_all
    order by creation_date ASC;

   
Example:- Sorting using DESC keyword

    select po_header_id, creation_date
    from po_headers_all
    order by creation_date DESC;
   

Example:- Sorting by relative position
You can also use the SQL ORDER BY clause to sort by relative position in the result set, where the first field in the result set is 1. The next field is 2, and so on....

    select po_header_id, creation_date
    from po_headers_all
    order by 1 ASC;   

   
Example:- Using both ASC and DESC keyword
When sorting your result set using the SQL ORDER BY clause, you can use the ASC and DESC attributes in a single SQL SELECT statement.

    select segment1, header_id, booked_date, creation_date
    from oe_order_headers_all
    order by booked_date ASC, creation_date DESC;
   
   
   
   

No comments:

Post a Comment