Just as you can sort data in Sheets, you can sort data
using SQL. You can use the
ORDER BY command to sort the rows returned by the
query by whatever criteria you like. As with sorting in Sheets, this applies
primarily to numeric and text columns.
For example, the following query returns the longest 10 bike trips ordered by duration.
The column name after the
ORDER BY clause specifies which column to use as
the sorting key, in this case
duration. In this example, the rows will be
ordered by their
duration column value in decreasing order. To specify
whether you want the rows sorted increasingly (lowest to highest, A-Z) or
decreasingly (highest to lowest, Z-A), use the
ASC (ascending) and
(descending) keywords respectively. In the example above, since you are sorting
by duration from highest to lowest,
DESC is used.
As in Sheets, you can apply filters using
WHERE and sort using
to show the top or bottom rows (sorted by some column) for a given subset of
data. For example, you can return the longest 10 rides by duration just starting
from station 31111.
In SQL, you can also order by multiple columns. In this case, the resulting rows
will be ordered by the values in the specified columns, ordered by the first
specified column, then the second specified column, and so forth. For example,
ORDER BY start_station, end_station, duration, the rows will first
be sorted by
start_station, then within each value of
rows will be ordered by
end_station, then within each pair of
end_station values, the rows will be ordered by
Now try to write SQL queries that will answer the following questions.