Partager via


SELECT - SQL Command - ORDER BY Clause

The ORDER BY clause specifies one or more items used to sort the final query result set and the order for sorting the results.

Note

If you do not specify an order in the ORDER BY clause, query results appear in no order.

For the complete syntax, see SELECT - SQL Command.

The detailed syntax for the ORDER BY clause appears as follows:

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

Parameters

  • [ORDER BY Order_Item
    Specifies the item used to sort the final query result set.

    • A field in a FROM table or a subquery. You cannot specify a Blob or General type field.

      Note

      If the ORDER BY clause is applied to a UNION operation, the field should also be a Select_Item in the last SELECT clause, not a subquery.

    • A field alias from the SELECT list.

      Note

      If the ORDER BY clause is applied to a UNION operation, the alias should be a Select_Item in the last SELECT clause.

    • A numeric expression indicating the location of the column in the result table. The leftmost column is number 1.

  • [ASC]
    Specifies an ascending order for the query results. ASC is the default order for ORDER BY.

  • [DESC]
    Specifies a descending order for the query results.

Remarks

The following code shows a summary of the main clauses of the SELECT - SQL Command:

SELECT Select_List
   FROM Table_List
...[WITH (BUFFERING = lExpr)]
   [WHERE Conditions]
   [GROUP BY Column_List]
   [HAVING Conditions]
   [UNION Clause]
   [ORDER BY Column_List]
   [INTO Clause | TO Clause ] 
   [Additional_Display_Options]

For more information about a particular clause of the SQL SELECT command, see the following topics:

Example

The following example organizes results of a query using the ORDER BY Order_Item clause. The example displays the Country, PostalCode, and Company fields for those records in the Customer table in ascending order, by default.

CLOSE ALL
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\TestData')
SELECT country, postalcode, company ;
   FROM customer ;
   ORDER BY country, postalcode, company

See Also

Reference

CREATE QUERY Command

CREATE TABLE - SQL Command

MODIFY QUERY Command

Other Resources

Working with Queries

Working with Views (Visual FoxPro)

Query and View Designers