Skip to Main Content
Programming ColdFusion MX, 2nd Edition
book

Programming ColdFusion MX, 2nd Edition

by Rob Brooks-Bilson
August 2003
Intermediate to advanced content levelIntermediate to advanced
1140 pages
68h 45m
English
O'Reilly Media, Inc.
Content preview from Programming ColdFusion MX, 2nd Edition

Sorting Query Results

When you use a basic SQL SELECT statement to retrieve records from a database, those records are returned in the order in which they are stored. If you want to change the order in which the records are displayed (which you probably do), you need to use an ORDER BY clause, as shown in Example 4-2.

Example 4-2. Sorting query results using the SQL ORDER clause

<cfquery name="GetEmployeeInfo" datasource="ProgrammingCF">
  SELECT Name, Title, Department, Email, PhoneExt
  FROM EmployeeDirectory
  ORDER BY Name ASC
</cfquery>
   
<html>
<head>
  <title>Sorting Query Results Using the SQL ORDER Clause</title>
  <style type="text/css">
    th {
      background-color : #888888;
      font-weight : bold;
      text-align : center;
    }
    td {
      background-color : #C0C0C0;
    }
  </style>          
</head>
   
<body>
<table cellpadding="3" cellspacing="1">
  <tr>
    <th>Name</th>
    <th>Title</th>
    <th>Department</th>
    <th>E-mail</th>
    <th>Phone Extension</th>
  </tr>    
  <cfoutput query="GetEmployeeInfo">
  <tr>
    <td>#Name#</td>
    <td>#Title#</td>
    <td>#Department#</td>
    <td><a href="Mailto:#Email#">#Email#</a></td>
    <td>#PhoneExt#</td>
  </tr>    
  </cfoutput>
</table>
</body>
</html>

The ORDER BY clause specifies which column or columns to use in ordering the query results. Sorting can be either ASC (ascending) or DESC (descending). Example 4-2 sorts the result set by name column, in ascending order. The output is shown in Figure 4-1.

Sorting a result set using the ORDER BY clause

Figure 4-1. Sorting a ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming ColdFusion

Programming ColdFusion

Rob Brooks-Bilson

Publisher Resources

ISBN: 0596003803Supplemental ContentErrata Page