SQL ORDER BY.

ORDER BY in the SELECT Statement.

  • ORDER BY is used for sorting the query results.
    ORDER BY Syntax within the SELECT statement:
    SELECT  select_list
      FROM table/view_list
      [WHERE search_conditions]
      [ORDER BY order_by_list ]
  • Most (but not all) systems RDBMS require that each item in the ORDER BY order_by_list also appears in the SELECT column_list.
  • ORDER BY can handle four types of expression in the sort:
    1. A column name.
    2. A column name including arithmetic operators or functions (price * 1.0825).
    3. A display label assigned to a column or expression in the SELECT clause.
    4. Column position numbers in the column list of a SELECT statement.
    Each expression in an ORDER BY can also be specified with:
    DESC Means; in DESCending order
    ASC Means; in ASCending order (default)
    Example using 2. and 3. Expression type:
    MySQL, Oracle, SQL server, PostgreSQL:
    select ISBN_no "ISBN", item_qty*PRICE "Order Sum" 
      from order_books
      where Isbn_no like '%8'
      OR Isbn_no like '0%'
      AND item_qty*PRICE < 100 
      ORDER BY ISBN_NO , item_qty*PRICE DESC;
    The result should be:
    ISBN Order Sum
    0201703092 78
    0471777781 64
    0672325764 49
    0764557599 84
    0764557599 42
    0764579088 140
    Example using 1. and 4. Expression type:
    MySQL, Oracle, SQL server, PostgreSQL:
    select ISBN_no "ISBN", item_qty*PRICE "Order Sum"
      from order_books
      where Isbn_no like '%8'
      OR Isbn_no like '0%'
      AND item_qty*PRICE < 100 
      order by ISBN_NO , 2 DESC;
    The result should be:
    ISBN Order Sum
    0201703092 78
    0471777781 64
    0672325764 49
    0764557599 84
    0764557599 42
    0764579088 140
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.