IBM Books

SQL Getting Started


Sorting Rows

You may want the information returned in a specific order. Use the ORDER BY clause to sort the information by the values in one or more columns.

The following statement displays the employees in department 84 ordered by number of years employed:

     SELECT NAME, JOB, YEARS
        FROM STAFF
        WHERE DEPT = 84
        ORDER BY YEARS

This statement produces the following result:

     NAME      JOB   YEARS 
     --------- ----- ------
     Davis     Sales      5
     Gafney    Clerk      5
     Edwards   Sales      7
     Quill     Mgr       10

Specify ORDER BY as the last clause in the entire SELECT statement. Columns named in this clause can be expressions or any column of the table. The column names in the ORDER BY clause do not have to be specified in the select list.

You can order rows in ascending or descending order by explicitly specifying either ASC or DESC within the ORDER BY clause. If neither is specified, the rows are automatically ordered in ascending sequence. The following statement displays the employees in department 84 in descending order by number of years employed:

     SELECT NAME, JOB, YEARS
        FROM STAFF
        WHERE DEPT = 84
        ORDER BY YEARS DESC

This statement produces the following result:

     NAME      JOB   YEARS 
     --------- ----- ------
     Quill     Mgr       10
     Edwards   Sales      7
     Davis     Sales      5
     Gafney    Clerk      5

You can order rows by character values as well as numeric values. The following statement displays the employees in department 84 in alphabetical order by name:

     SELECT NAME, JOB, YEARS
        FROM STAFF
        WHERE DEPT = 84
        ORDER BY NAME

This statement produces the following result:

 
     NAME      JOB   YEARS 
     --------- ----- ------
     Davis     Sales      5
     Edwards   Sales      7
     Gafney    Clerk      5
     Quill     Mgr       10


[ Top of Page | Previous Page | Next Page | Table of Contents | Index ]

[ DB2 List of Books | Search the DB2 Books ]