ORDER BY Clause

Sorts a query result set on one or more columns.

Syntax

ORDER BY expression [ ASC | DESC ] [, ...]

Parameters

expression

One of the following:

  • Name or ordinal number of a SELECT list item. You cannot use an integer value for an ORDER BY clause that is inside an analytic function's OVER clause.
  • Arbitrary expression formed from columns that do not appear in the SELECT list
  • CASE expression

Notes

Examples

The follow example returns all the city and deal size for customer Metamedia, sorted by deal size in descending order.

=> SELECT customer_city, deal_siz FROM customer_dimension WHERE customer_name = 'Metamedia'
   ORDER BY deal_size DESC;	
  customer_city   | deal_size
------------------+-----------
 El Monte         |   4479561
 Athens           |   3815416
 Ventura          |   3792937
 Peoria           |   3227765
 Arvada           |   2671849
 Coral Springs    |   2643674
 Fontana          |   2374465
 Rancho Cucamonga |   2214002
 Wichita Falls    |   2117962
 Beaumont         |   1898295
 Arvada           |   1321897
 Waco             |   1026854
 Joliet           |    945404
 Hartford         |    445795
(14 rows)

The following example uses a transform function. It returns an error because the ORDER BY column is not in the window partition.

=> CREATE TABLE t(geom geometry(200), geog geography(200)); 
=> SELECT PolygonPoint(geom) OVER(PARTITION BY geom) 
   AS SEL_0 FROM t ORDER BY geog;
ERROR 2521: Cannot specify anything other than user defined transforms and partitioning expressions in the ORDER BY list 

The following example, using the same table, corrects this error.

=> SELECT PolygonPoint(geom) OVER(PARTITION BY geom) 
   AS SEL_0 FROM t ORDER BY geom;