Home » How to Use Proc Sort in SAS (With Examples)

How to Use Proc Sort in SAS (With Examples)

by Erma Khan

You can use proc sort in SAS to order the observations in a dataset by one or more variables.

The following examples show how to use this procedure with the following dataset in SAS:

/*create dataset*/
data original_data;
    input team $ points rebounds;
    datalines;
A 12 8
A 12 7
A 14 5
A 23 9
A 20 12
A 11 7
A 14 7
B 20 2
B 20 5
B 29 4
B 14 7
B 19 8
B 17 9
B 30 9
;
run;

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

Example 1: Sort Observations Ascending

We can use proc sort to sort the observations in the dataset in ascending order (smallest to largest) based on the value in the points column:

/*sort by points ascending*/
proc sort data=original_data out=data2;
    by points;
run;

/*view sorted dataset*/
proc print data=data2;

SAS proc sort ascending

Notice that the observations are sorted in ascending order based on the value in the points column.

Example 2: Sort Observations Descending

We can use proc sort with the descending statement to sort the observations in the dataset in descending order (largest to smallest) based on the value in the points column:

/*sort by points descending*/
proc sort data=original_data out=data3;
    by descending points;
run;

/*view sorted dataset*/
proc print data=data3;

SAS proc sort descending

Notice that the observations are sorted in ascending order based on the value in the points column.

Example 3: Sort Observations by Multiple Columns

We can use proc sort with multiple variables listed in the by statement to sort the observations in the dataset by multiple variables.

The following code shows how to sort the observations in the dataset by the value in the points column ascending, then by the value in the rebounds column ascending:

/*sort by points ascending, then by rebounds ascending*/
proc sort data=original_data out=data4;
    by points rebounds;
run;

/*view sorted dataset*/
proc print data=data4;

Notice that the observations are sorted by the value in the points column ascending, then by the value in the rebounds column ascending.

Additional Resources

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

How to Use Proc Append in SAS
How to Use Proc Tabulate in SAS
How to Use Proc Rank in SAS

Related Posts