ORDER BY

The Historian OLE DB Provider supports the use of ORDER BY in a SELECT statement. If you do not specify ORDER BY, the output of the row order cannot be assumed. For example, if you want to order the rows returned from the ihCollectors table by the CollectorName column, you would need to include that column name in ORDER BY. As a more common example, when requesting timestamps with data, you should use the Timestamp column with ORDER BY to ensure that the samples are sorted in order by time.

ORDER BY sorts the returned records by one or more specified columns in either ascending or descending order. If you do not specify ascending or descending, ORDER BY uses ascending order. You can order results by one or more columns. If you sort by multiple columns, the sorting priority begins with the first column listed in the query, and then the next column, and so on.

If you specify ascending or descending order with ORDER BY, use the abbreviations in the following table or spell out the whole word.

Table 1. ORDER BY Abbreviations
AbbreviationDescription
ASCSpecifies that the values should be sorted in ascending order, from lowest value to highest value.
DESCSpecifies that the values should be sorted in descending order, from highest value to lowest value.

The Historian OLE DB Provider treats Null values as the lowest possible values. It processes ORDER BY before it performs any RowCount truncation.

The following examples display simple and more complex examples of ORDER BY in actual SQL statements.

Example 1: Retrieve Collectors in Descending Order Sorted by CollectorName Column

SELECT * FROM ihcollectors ORDER BY collectorname DESC

Example 2: Retrieve Messages in Ascending Order Sorted by Time and Other Columns

SELECT * FROM ihmessages
WHERE timestamp>='5-oct-2001 00:00:00' 
AND timestamp<='18-jan-2002 00:00:00'
ORDER BY timestamp, topic, username, messagenumber, messagestring