Java Reference
In-Depth Information
order.
SELECT *
FROM CUSTOMERS
WHERE Last_Name = 'Corleone'
ORDER BY First_Name DESC;
Sorting on multiple columns is also easy to do by using a sort list. For example, to sort the data in
ascending order based on Last_Name and then sort duplicates using the First_Name in descending
order, the sort list is as follows:
ORDER BY Last_Name, First_Name DESC;
The entire SQL statement to sort the data in ascending order based on Last_Name and then sort
duplicates using the First_Name in descending order is shown below .
SELECT First_Name, MI, Last_Name, Street, City, State, Zip
FROM CUSTOMERS
ORDER BY Last_Name, First_Name DESC;
Note
When no ORDER BY clause is used, the order of the output of a query is undefined.
These are the rules for using
ORDER BY
:
ORDER BY
must be the last clause in the
SELECT
statement.
Default sort order is ascending.
You can specify ascending order with the keyword ASC.
You can specify descending order with the keyword DESC.
You can use column names or expressions in the
ORDER BY
clause.
The column names in the
ORDER BY
clause do not have to be specified in the select list.
NULLS
usually occur first in the sort order.
Note
The DatabaseMetaData object provides a number of methods:
boolean nullsAreSortedAtStart()
boolean nullsAreSortedAtEnd()
These methods can be used to determine the sort order for NULLs when in doubt.
Another common reporting requirement is to break down the data a query returns into various groups
so that the data can be analyzed in some way. The
GROUP BY
clause, discussed in the
next section
,
enables you to combine database records to perform calculations such as averages or counts on
groups of records.
The GROUP BY Clause