Database Reference
In-Depth Information
▼
Analysis
The
DESC
keyword applies only to the column name that directly precedes it.
In the previous example,
DESC
was specified for the
prod_price
column, but
not for the
prod_name
column. Therefore, the
prod_price
column is sorted
in descending order, but the
prod_name
column (within each price) is still
sorted in standard ascending order.
Tip
Sorting Descending on Multiple Columns If you want to sort descending on multiple
columns, be sure each column has its own
DESC
keyword.
The opposite of
DESC
is
ASC
(for
ascending
), which may be specified to sort in
ascending order. In practice, however,
ASC
is not usually used because ascend-
ing order is the default sequence (and is assumed if neither
ASC
nor
DESC
are
specified).
Tip
Case Sensitivity and Sort Orders When you are sorting textual data, is
A
the same as
a
? And does
a
come before
B
or after
Z
? These are not theoretical questions, and the
answers depend on how the database is set up.
In
dictionary
sort order,
A
is treated the same as
a
, and that is the default behavior in
MariaDB (and indeed most DBMSs). However, administrators can change this behavior if
needed. (If your database contains many foreign language characters, this might become
necessary.)
The key here is that, if you do need an alternate sort order, you cannot accomplish it
with a simple
ORDER BY
clause. You need to use the
CONVERT()
function (functions
are introduced in Chapter 11, “Using Data Manipulation Functions”) or contact your data-
base administrator if you need the column character set changed.
Using a combination of
ORDER BY
and
LIMIT
, it is possible to find the highest
or lowest value in a column. The following example demonstrates how to find
the value of the most expensive item:
▼
Input
SELECT prod_price
FROM products
ORDER BY prod_price DESC
LIMIT 1;