You can order the rows in a query result. That is, you can name a particular column or set of columns whose values determine the order of rows in the result set. There are several ways in which you can use ordering:
SELECT *
FROM titles
ORDER BY price
On the other hand, if you want to arrange the titles with the more expensive books first, you can explicitly specify a highest-first ordering. That is, you indicate that the result rows should be arranged by descending values of the price column. The resulting SQL might look like this:
SELECT *
FROM titles
ORDER BY price DESC
SELECT *
FROM authors
ORDER BY state, city
SELECT title_id, title
FROM titles
ORDER BY price DESC
SELECT title, price * royalty / 100 as royalty_per_unit
FROM titles
ORDER BY royalty_per_unit DESC
(The formula for calculating the royalty that each book earns per copy is emphasized.)
To calculate a derived column, you can use SQL syntax, as in the preceding example, or you can use a user-defined function that returns a scalar value. For more information about user-defined functions, see User-Defined Functions.
SELECT city, state, COUNT(*)
FROM authors
GROUP BY city, state
ORDER BY COUNT(*) DESC, state
(Notice that the query uses state as a secondary sort column. Thus, if two states have the same number of authors, those states will appear in alphabetical order.)
SELECT title
FROM
authors
INNER JOIN
titleauthor
ON authors.au_id
= titleauthor.au_id
INNER JOIN
titles
ON titleauthor.title_id
= titles.title_id
WHERE
au_fname = 'Halldor' AND
au_lname = 'Laxness'
ORDER BY
title COLLATE SQL_Icelandic_Pref_CP1_CI_AS
For more information about sorting result rows, see Ordering Query Results.