Power Selecting - Order By
(Page 2 of 6 )
The results of a query may not necessarily be returned in the desired order. Consider a query to return the first and last names from the Clients table.
SELECT LastName, FirstName from Clients;
LastName FirstName ------------------ LaBelle Nathan Adams Gwendolyn Smith Harold Chavez Jose Adams Joseph Copland Dorothy Johnson Diane Smith Aaron Franklin Susanna Wilson Jessica Brown Michael Smith Josh |
The results from a query statement are returned in a seemingly arbitrary order.
One of the main advantages of a database server is its ability to sort large amounts of information quickly, so it makes sense to have the database sort the results instead of scripting a sort routine to do so. ORDER BY can be used to return sorted results.
ORDER BY accepts the columns that will act as sort indexes and then ASC for an ascending sort order or DESC for a descending sort order.
SELECT LastName, FirstName from Clients ORDER BY LastName ASC;
LastName FirstName ------------------ Adams Gwendolyn Adams Joseph Brown Michael Chavez Jose Copland Dorothy Franklin Susanna Johnson Diane LaBelle Nathan Smith Harold Smith Aaron Smith Josh Wilson Jessica |
By specifying an ascending sort order based on the LastName column, results are returned alphabetically based on the client's last name.
Notice, however, a closer look reveals the entire results set is not completely alphabetical (as illustrated by the three Smiths, Harold, Aaron and Josh). Multiple sorting criteria may be specified.
SELECT LastName, FirstName from Clients ORDER BY LastName ASC, FirstName ASC;
LastName FirstName ------------------ Adams Gwendolyn Adams Joseph Brown Michael Chavez Jose Copland Dorothy Franklin Susanna Johnson Diane LaBelle Nathan Smith Aaron Smith Harold Smith Josh Wilson Jessica |
Next: Distinct >>
More Database Articles Articles
More By bluephoenix