SORT Procedure

The SORT procedure sorts observations in a SAS data set by one or more variables, storing the resulting observations in a new data set or replacing the original. PROC SORT is used most often for sorting a data set so that other SAS procedures can process it in subsets using BY statements.


General form, SORT procedure:
PROC SORT <option(s)>;
BY <DESCENDING> variable-1
     <...<DESCENDING> variable-n>;

where option(s) includes the DATA= and OUT= data set options.


PROC SORT rearranges the observations in a data set according to the values of the variables in the BY statement. Multiple sort variables may be used.


Specifying Output
 
Hot tip: Specifying an output data set can be crucial when using PROC SORT. By default, the SORT procedure overwrites the current data set with newly sorted observations. To preserve your original data, include the OUT= option and specify an output data set. Then use the DATA= option in later programming steps to read the sorted observations.

For example, the SORT procedure shown below sorts the observations of the data set Finance.Credit by the values of the variable Account. Because Finance.Credit is overwritten, its orginal order is lost.

SAS Data Set Finance.Credit (before SORT)

Account Name Type Transaction
1118 ART CONTUCK D 57.6
2287 MICHAEL WINSTONE D 145.8
6201 MARY WATERS C 45.0
7821 MICHELLE STANTON A 304.4
6621 WALTER LUND C 234.7
1086 KATHERINE MORRY A 64.9
556 LEE McDONALD D 70.8
7821 ELIZABETH WESTIN C 188.2
265 JEFFREY DONALDSON C 78.9
1010 MARTIN LYNN D 150.5

 


     proc sort data=finance.credit;
        by account;
     run;

SAS Data Set Finance.Credit (after SORT)

Account Name Type Transaction
265 JEFFREY DONALDSON C 78.9
556 LEE McDONALD D 70.8
1010 MARTIN LYNN D 150.5
1086 KATHERINE MORRY A 64.9
1118 ART CONTUCK D 57.6
2287 MICHAEL WINSTONE D 145.8
6201 MARY WATERS C 45.0
6621 WALTER LUND C 234.7
7821 MICHELLE STANTON A 304.4
7821 ELIZABETH WESTIN C 188.2

 


Including the OUT= option preserves your original data. In this case, the sorted version of Finance.Credit is the newly created data set Work.Credsort.
     proc sort data=finance.credit out=work.credsort;
        by account;
     run;

Specifying Sort Order

The default SORT procedure order is ascending, but can be reversed by including the DESCENDING keyword before any variable in the BY statement.

     proc sort data=finance.credit out=work.credsort;
        by descending account;
     run;

SAS Data Set Work.Credsort

Account Name Type Transaction
7821 MICHELLE STANTON A 304.4
7821 ELIZABETH WESTIN C 188.2
6621 WALTER LUND C 234.7
6201 MARY WATERS C 45.0
2287 MICHAEL WINSTONE D 145.8
1118 ART CONTUCK D 57.6
1086 KATHERINE MORRY A 64.9
1010 MARTIN LYNN D 150.5
556 LEE McDONALD D 70.8
265 JEFFREY DONALDSON C 78.9

 





Copyright © 2002 SAS Institute Inc., Cary, NC, USA. All rights reserved.

Terms of Use & Legal Information | Privacy Statement