Sorting with Oracle
Sometimes it is necessary that the rows returned from your query
to be in a specific order. For example, I might want scores from
high to low or names in alphabetical order. By default, the
database will sort data ascending, smallest to largest. Words are
sorted alphabetically. NULLs cannot be sorted, they will be listed
as found at the bottom of the results.
To sort the results set, we use the ORDER BY clause.
order by author_last_name;
The Oracle ORDER BY clause must be used if you
require that the rows be sorted. The Oracle database, by default,
will not sort the results set, nor does it store rows in a table in a
The Oracle ORDER BY clause is important because internally, the Oracle database uses a HEAP organized
table as its default table. A HEAP table stores new data in the
first available slot. Once you start adding and deleting rows in
your table, the row order becomes random. Different queries (and
for that matter, the same query run at different times) will use
different execution plans to retrieve the requested data. Thus,
the results can be ordered differently if you do not use the Oracle
Let's look at the AUTHOR table.
The only way to insure that the rows are ordered is to use
the Oracle ORDER BY clause. Also,
sorting is always performed last. It makes no sense to sort an
intermediate row set that we will never see.
Let's now take a look at the
Oracle ORDER BY clause.
In the first query, we retrieved the
author_last_name from the
author table. The rows were returned as the database found them.
In the second example, we executed the same query except that we used
the Oracle ORDER BY clause to order them alphabetically by last name.
Notice that the default is ascending. In the next example, we
again selected the author's last name, but we used Oracle ORDER BY to order them by
order by author_key desc;
Notice in the example above that I did not select
the author_key even though I
used it in the Oracle ORDER BY
Related Oracle ORDER BY information:
Sorting, Grouping, Table Joins, and Subqueries
Internals of Oracle Sort Operations