SAS: How to Use ORDER BY in PROC SQL


You can use the ORDER BY statement in PROC SQL in SAS to order the results of a query by the values of one or more variables.

Here are three common ways to use the ORDER BY statement in practice:

Method 1: Order By One Variable Ascending

/*display results in ascending order by value in team column*/
proc sql;
   select *
   from my_data
   order by team;
quit;

Method 2: Order By One Variable Descending

/*display results in descending order by value in team column*/
proc sql;
   select *
   from my_data
   order by team desc;
quit;

Method 3: Order By Multiple Variables

/*display results in ascending order by team, then descending order by points*/
proc sql;
   select *
   from my_data
   order by team, points desc;
quit;

The following examples show how to use each method in practice with the following dataset in SAS that contains information about various basketball players:

/*create dataset*/
data my_data;
    input team $ position $ points assists;
    datalines;
A Guard 14 4
B Guard 22 6
B Guard 24 9
A Forward 13 8
C Forward 13 9
A Guard 10 5
B Guard 24 4
C Guard 22 6
D Forward 34 2
D Forward 15 5
B Forward 23 5
B Guard 10 4
;
run;

/*view dataset*/
proc print data=my_data;

Example 1: Order By One Variable Ascending

The following code shows how to return every row in the dataset in ascending order by the values in the team column:

/*display results in ascending order by value in team column*/
proc sql;
   select *
   from my_data
   order by team;
quit;

Notice that the results are shown in ascending order by the values in the team column.

Example 2: Order By One Variable Descending

The following code shows how to return every row in the dataset in descending order by the values in the team column:

/*display results in descending order by value in team column*/
proc sql;
   select *
   from my_data
   order by team desc;
quit;

Notice that the results are shown in descending order by the values in the team column.

Example 3: Order By Multiple Variables

The following code shows how to return every row in the dataset first in ascending order by team, then in descending order by points:

/*display results in ascending order by team, then descending order by points*/
proc sql;
   select *
   from my_data
   order by team, points desc;
quit;

Notice that the results are shown first in ascending order by team, then in descending order by points.

Additional Resources

The following tutorials explain how to perform other common tasks in SAS:

SAS: How to Use UNION in PROC SQL
SAS: How to Use EXCEPT in PROC SQL
SAS: How to Use the IN Operator in PROC SQL
SAS: How to Use the WHERE Operator in PROC SQL

Leave a Reply

Your email address will not be published. Required fields are marked *