In a SELECT query, rows are displayed in an undetermined
order. To guarantee that the rows will be returned from SELECT
in a specific order, you must add the ORDER BY clause to
the end of the SELECT. Figure shows
the use of ORDER BY.
test=> SELECT * FROM friend ORDER BY state;
firstname | lastname | city | state | age
-----------------+----------------------+-----------------+-------+-----
Cindy | Anderson | Denver | CO | 23
Mike | Nichols | Tampa | FL | 20
Sam | Jackson | Allentown | PA | 22
(3 rows)
You can reverse the order by adding
DESC, as shown in Figure .
test=> SELECT * FROM friend ORDER BY age DESC;
firstname | lastname | city | state | age
-----------------+----------------------+-----------------+-------+-----
Cindy | Anderson | Denver | CO | 23
Sam | Jackson | Allentown | PA | 22
Mike | Nichols | Tampa | FL | 20
(3 rows)
If the query also used a WHERE clause, the ORDER
BY would appear after the WHERE clause, as in Figure .
test=> SELECT * FROM friend WHERE age >= 21 ORDER BY firstname;
firstname | lastname | city | state | age
-----------------+----------------------+-----------------+-------+-----
Cindy | Anderson | Denver | CO | 23
Sam | Jackson | Allentown | PA | 22
(2 rows)
You can ORDER BY more than one column by specifying multiple column names or labels, separated by commas. The command would then sort by the first column specified. For rows with equal values in the first column, it would sort based on the second column specified. Of course, this approach is not useful in the friend example because all column values are unique.