Database Reference
In-Depth Information
| JP1000 | 35.00 | JetPack 1000 |
| SAFE | 50.00 | Safe |
| JP2000 | 55.00 | JetPack 2000 |
+---------+------------+----------------+
It is important to understand that when you are sorting by multiple columns,
the sort sequence is exactly as specified. In other words, using the output in
the previous example, the products are sorted by the
prod_name
column only
when multiple rows have the same
prod_price
value. If all the values in the
prod_price
column had been unique, no data would have been sorted by
prod_name
.
Tip
An
ORDER BY
Shortcut Instead of type the column names in
ORDER BY
, you can
also type the column number specifying its sequence in the
SELECT
statement. This
statement:
SELECT prod_id, prod_price, prod_name
FROM products
ORDER BY prod_price, prod_name;
is functionally identical to this statement:
SELECT prod_id, prod_price, prod_name
FROM products
ORDER BY 2, 3;
Obviously, this syntax can save you some typing. But, keep in mind that if you do use
this shortcut, then your
ORDER BY
statement will essentially break if you ever make
changes to the
SELECT
columns.
Data sorting is not limited to ascending sort orders (from
A
to
Z
). Although
this is the default sort order, the
ORDER BY
clause can also be used to sort in
descending order (from
Z
to
A
). To sort by descending order, the keyword
DESC
must be specified.
The following example sorts the products by price in descending order (most
expensive first):
▼
Input
SELECT prod_id, prod_price, prod_name
FROM products
ORDER BY prod_price DESC;