1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
8 CONTENT="Modular DocBook HTML Stylesheet Version 1.7"><LINK
10 HREF="mailto:pgsql-docs@postgresql.org"><LINK
12 TITLE="PostgreSQL 7.4.1 Documentation"
13 HREF="index.html"><LINK
16 HREF="queries.html"><LINK
18 TITLE="Combining Queries"
19 HREF="queries-union.html"><LINK
21 TITLE="LIMIT and OFFSET"
22 HREF="queries-limit.html"><LINK
25 HREF="stylesheet.css"><META
27 CONTENT="2003-12-22T03:48:47"></HEAD
33 SUMMARY="Header navigation table"
43 >PostgreSQL 7.4.1 Documentation</TH
51 HREF="queries-union.html"
67 >Chapter 7. Queries</TD
81 HREF="queries-limit.html"
105 > After a query has produced an output table (after the select list
106 has been processed) it can optionally be sorted. If sorting is not
107 chosen, the rows will be returned in random order. The actual
108 order in that case will depend on the scan and join plan types and
109 the order on disk, but it must not be relied on. A particular
110 output ordering can only be guaranteed if the sort step is explicitly
117 > clause specifies the sort order:
126 >table_expression</VAR
148 >, etc., refer to select list
149 columns. These can be either the output name of a column (see
151 HREF="queries-select-lists.html#QUERIES-COLUMN-LABELS"
153 >) or the number of a column. Some
156 CLASS="PROGRAMLISTING"
157 >SELECT a, b FROM table1 ORDER BY a;
158 SELECT a + b AS sum, c FROM table1 ORDER BY sum;
159 SELECT a, sum(b) FROM table1 GROUP BY a ORDER BY 1;</PRE
163 > As an extension to the SQL standard, <SPAN
166 > also allows ordering
167 by arbitrary expressions:
169 CLASS="PROGRAMLISTING"
170 >SELECT a, b FROM table1 ORDER BY a + b;</PRE
172 References to column names in the <TT
176 renamed in the select list are also allowed:
178 CLASS="PROGRAMLISTING"
179 >SELECT a AS b FROM table1 ORDER BY a;</PRE
181 But these extensions do not work in queries involving
192 and are not portable to other SQL databases.
195 > Each column specification may be followed by an optional
202 > to set the sort direction to
203 ascending or descending. <TT
206 > order is the default.
207 Ascending order puts smaller values first, where
211 > is defined in terms of the
215 > operator. Similarly, descending order is
216 determined with the <TT
230 > If more than one sort column is specified, the later entries are
231 used to sort rows that are equal under the order imposed by the
232 earlier sort columns.
249 HREF="queries-order.html#AEN3101"
267 > for the column's data type to determine the sort
275 data types will be set up so that the <TT
282 > operators correspond to this sort ordering,
283 but a user-defined data type's designer could choose to do something
294 SUMMARY="Footer navigation table"
305 HREF="queries-union.html"
323 HREF="queries-limit.html"
333 >Combining Queries</TD