Previous Topic: Exercise 3-6Next Topic: Exercise 3-7


Organizing Data

When you retrieve data from the database, the rows are in an order selected by the database management system. If you want the data sorted in a particular order, use the ORDER BY clause. The ORDER BY clause must be the last clause in a SELECT statement.

How It's Done

You can order an employee list by entering:

select emp_id, emp_lname
       from employee
       order by emp_lname;

The result looks like this:

 EMP_ID  EMP_LNAME  ------  ---------    2180  Albertini    1765  Alexander    2461  Anderson    1003  Baldwin    2466  Bennett    4321  Bradley    3082  Brooks    2096  Carlson    2145  Catlin    4008  Clark    4027  Courtney    3433  Crane    3841  Cromwell    4773  Dexter    3769  Donelson    5103  Ferguson    3778  Ferndale    5008  Fordman    1034  Gallway    2894  Griffin    4703  Halloran    2246  Hamel    2598  Jacobs    2004  Johnson    3294  Johnson    3199  Loren    3767  Lowe    2448  Lynn    4660  MacGregor    1234  Mills    3704  Moore    3764  Park    2010  Parker    4358  Robinson    4002  Roy    3288  Sampson    2209  Smith    3341  Smith    2299  Spade    3449  Taylor    4001  Thompson    2437  Thompson    4456  Thompson    2781  Thurston    2898  Umidy    3222  Voltmer    3338  White    4962  White    2106  Widman    2424  Wilder    3991  Wilkins    3411  Williams    5090  Wills    3118  Wooding    2174  Zander  55 rows processed

You can specify either ascending (ASC) or descending (DESC) order. The default order is ascending.

If you sort on a column that contains null values, the null values are grouped together.