Database Toolbox Previous page   Next Page

Order By

Use the Order by function to specify the order in which results are sorted.

After selecting Fields in the Visual Query Builder dialog box, click Order by in Advanced query options. The Order By Clauses dialog box appears.

Order By Clauses Dialog Box

  1. From Fields, select the field to which you want to assign a sort order for the results.
  2. Type the Sort key number. If you are specifying only one field for sorting, accept the default, 1.
  3. Select the Sort order, either Ascending or Descending.
  4. To create the clause, click Apply.
  1. The clause appears in the Current clauses area.

    To specify additional fields for sorting, repeat steps 1 through 4. For the Sort key number, type an integer; this specifies that the field will be sorted first, second, etc. If you do not specify the Sort key number, it will have the highest number when added to the Current clauses area. Clauses appear in ascending order by sort key number.

  1. To change a clause, select it in the Current clauses area and click Edit. Make changes for that clause and click Apply.
  1. To remove a clause, select the clause and then click Delete. Use Ctrl+click or Shift+click to select multiple clauses to delete.

    Changes automatically update the Sort key number of the other clauses.

  1. Click OK.
  1. The Order By Clauses dialog box closes. The SQL statement in the Visual Query Builder dialog box reflects the order-by clause.

Example Using Order By Clauses

This example retrieves sales volumes for January and February by stock number, and sorts the results first in increasing order for January sales, and then in decreasing order for February sales:

  1. In the Visual Query Builder dialog box, select the fields stockNumber, January, and February from the salesVolume table.
  2. In Advanced query options, click Order by.
  1. The Order By Clauses dialog box appears.

  1. For January, specify the Sort key number to be 1 and for the Sort order, select Ascending; then click Apply. For February, specify the Sort key number to be 2 and for the Sort order, select Descending; then click Apply (shown below).

  2. Click OK.
  1. The Order By Clauses dialog box closes. The SQL statement in the Visual Query Builder dialog box reflects the order-by clause conditions you specified.

  1. Assign a MATLAB workspace variable and click Execute to run the query. From the results you can see that column 1 (stock number) is in no particular order, and column 2 (January sales volume) is in increasing order because the Sort key number specified for January was 1. Where the values in column 2 are the same (3000), the values in column 3 (February sales) are in descending order (2400, 2400, and 1500) because the Sort key number specified for February was 2, and the Sort order was Descending.


Previous page  Having SQL Statement or MATLAB Command Next page

© 1994-2005 The MathWorks, Inc.