Sort a data set by ascending or descending variables using PROC SORT in SAS

Consider the built-in data set SASHELP.CLASS in SAS.  Here are the first 5 observations from PROC PRINT.

Obs Name Sex Age Height Weight
1 Joyce F 11 51.3 50.5
2 Thomas M 11 57.5 85.0
3 James M 12 57.3 83.0
4 Jane F 12 59.8 84.5
5 John M 12 59.0 99.5

As you can clearly see, they are NOT sorted by weight.  Here is how you can sort the data set by weight using PROC SORT.

```proc sort
data = sashelp.class
out = class1;
by weight;
run;```

Here are the first 5 observations of CLASS1.

Obs Name Sex Age Height Weight
1 Joyce F 11 51.3 50.5
2 Louise F 12 56.3 77.0
3 James M 12 57.3 83.0
4 Alice F 13 56.5 84.0
5 Jeffrey M 13 62.5 84.0

For CLASS1, the weights were sorted from smallest to largest.  How would you sort them from largest to smallest?  Here is the code to do so.

```proc sort
data = sashelp.class
out = class2;
by descending weight;
run;```

Note that I need to invoke the DESCENDING option in the BY statement.   (By default, the BY statement sorts observations in ascending order, and there is no ASCENDING option for the BY statement.)

Here are the first 5 observations of CLASS2.

Obs Name Sex Age Height Weight
1 Philip M 16 72.0 150.0
2 Ronald M 15 67.0 133.0
3 Robert M 12 64.8 128.0
4 Alfred M 14 69.0 112.5
5 Janet F 15 62.5 112.5

You can sort a data set using multiple variables.  Suppose that you want to sort SASHELP.CLASS

a) in ascending order by age

b) in descending order by weight

Here is the code for doing so.

```proc sort
data = sashelp.class
out = class3;
by   age
descending weight;
run;```

Here are the first 7 observations of CLASS3; I chose 7 observations because I wanted to show all observations of the first 2 ages (11 and 12).

Obs Name Sex Age Height Weight
1 Thomas M 11 57.5 85.0
2 Joyce F 11 51.3 50.5
3 Robert M 12 64.8 128.0
4 John M 12 59.0 99.5
5 Jane F 12 59.8 84.5
6 James M 12 57.3 83.0
7 Louise F 12 56.3 77.0

If you want to sort multiple variables in descending order, you must specify the DESCENDING option in front of every variable to be sorted in this way.  As an example, suppose that I want to sort SASHELP.CLASS

a) in descending order by age

b) in ascending order by sex

c) in descending order by weight.

Here is the code for doing so.

```proc sort
data = sashelp.class
out = class4;
by   descending age
sex
descending weight;
run;```

Here are the first 9 observations of CLASS4.

Obs Name Sex Age Height Weight
1 Philip M 16 72.0 150.0
2 Janet F 15 62.5 112.5
3 Mary F 15 66.5 112.0
4 Ronald M 15 67.0 133.0
5 William M 15 66.5 112.0
6 Carol F 14 62.8 102.5
7 Judy F 14 64.3 90.0
8 Alfred M 14 69.0 112.5
9 Henry M 14 63.5 102.5

In later blog posts, I will show how to do the same things in R and in PROC SQL.