Contents Index The HAVING clause: selecting groups of data Explicitly limiting the number of rows returned by a query

ASA SQL User's Guide
  Summarizing, Grouping and Sorting Query Results

The ORDER BY clause: sorting query results


The ORDER BY clause allows sorting of query results by one or more columns. Each sort can be ascending (ASC) or descending (DESC). If neither is specified, ASC is assumed.

A simple example 

The following query returns results ordered by name:

SELECT id, name
FROM product
ORDER BY name
id name
400 Baseball Cap
401 Baseball Cap
700 Shorts
600 Sweatshirt
... ...
Sorting by more than one column 

If you name more than one column in the ORDER BY clause, the sorts are nested.

The following statement sorts the shirts in the product table first by name in ascending order, then by quantity (descending) within each name:

SELECT id, name, quantity
FROM product
WHERE name like '%shirt%'
ORDER BY name, quantity DESC
id name quantity
600 Sweatshirt 39
601 Sweatshirt 32
302 Tee Shirt 75
301 Tee Shirt 54
... ... ...
Using the column position 

You can use the position number of a column in a select list instead of the column name. Column names and select list numbers can be mixed. Both of the following statements produce the same results as the preceding one.

SELECT id, name, quantity
FROM product
WHERE name like '%shirt%'
ORDER BY 2, 3 DESC
SELECT id, name, quantity
FROM product
WHERE name like '%shirt%'
ORDER BY 2, quantity DESC

Most versions of SQL require that ORDER BY items appear in the select list, but Adaptive Server Anywhere has no such restriction. The following query orders the results by quantity, although that column does not appear in the select list:

SELECT id, name
FROM product
WHERE name like '%shirt%'
ORDER BY 2, quantity DESC
ORDER BY and NULL 

With ORDER BY, NULL sorts before all other values in ascending sort order.

ORDER BY and case sensitivity 

The effects of an ORDER BY clause on mixed-case data depend on the database collation and case sensitivity specified when the database is created.


Explicitly limiting the number of rows returned by a query
ORDER BY and GROUP BY

Contents Index The HAVING clause: selecting groups of data Explicitly limiting the number of rows returned by a query