Полезная информация

next up previous contents index
Next: Destroying Tables Up: Five Basic SQL Commands Previous: Modifying Data with UPDATE

Sorting Data with ORDER BY

In a SELECT query, rows are displayed in an undetermined order. If you want to guarantee that the rows are returned from a SELECT in a specific order, you need to add the ORDER BY clause to the end of the SELECT. Figure [*] shows the use of ORDER BY.

  
Figure: Use of ORDER BY
\begin{figure}\begin{list}{}{
\setlength{\rightmargin}{\leftmargin}
\raggedrigh...
...vert Allentown~~~~~~\vert PA~~~\vert~22
\par (3~rows)\end{list}\par
\end{figure}

You can reverse the order by adding DESC, as seen in figure [*].
  
Figure: Reverse ORDER BY
\begin{figure}\begin{list}{}{
\setlength{\rightmargin}{\leftmargin}
\raggedrigh...
...vert Tampa~~~~~~~~~~\vert FL~~~\vert~20
\par (3~rows)\end{list}\par
\end{figure}

If the query were to use a WHERE clause too, the ORDER BY would appear after the WHERE clause, as in figure [*].
  
Figure: Use of ORDER BY and WHERE
\begin{figure}\begin{list}{}{
\setlength{\rightmargin}{\leftmargin}
\raggedrigh...
...vert Allentown~~~~~~\vert PA~~~\vert~22
\par (2~rows)\end{list}\par
\end{figure}

You can ORDER BY more than one column by specifying multiple column names or labels, separated by commas. It would sort by the first column, and for rows with equal values in the first column, it would sort based on the second column specified. Of course, this does not make sense in the the friends example because all columns are unique.


next up previous contents index
Next: Destroying Tables Up: Five Basic SQL Commands Previous: Modifying Data with UPDATE
Bruce Momjian
1999-11-21