Written and maintained by CASRAI Editorial Board
Published
On this page
PROC SORT in SAS orders dataset observations by one or more variables in a BY statement. Use DATA= to name the input and a different OUT= dataset to preserve it; add DESCENDING before each variable that needs reverse order. Sorting retains records unless you request a filtering option such as NODUPKEY, which keeps one observation per complete BY key.
For research data preparation, the important distinction is between changing record order and changing which records remain. The worked example below follows the same five fictional records through both operations, including the identity of the record removed by key-based deduplication.
What it is used for in research
Researchers and analysts use sorting to place repeated observations together, prepare data for BY-group processing, and inspect records in a meaningful sequence. SAS’s SORT documentation defines the operation in terms of observations and character or numeric variables: the variables identify the ordering keys, while the remaining values travel with their observations. Sorting a score column does not detach those scores from their participant identifiers.
A useful research distinction is the unit of observation. One participant can legitimately have several visit records. Ordering by participant and visit groups those records without declaring any of them redundant. Removing repeated participant identifiers alone would instead leave only one record for each participant, which may discard valid longitudinal observations. The choice of key therefore expresses an analytical decision, not a cosmetic display preference.
Check the available variable names and their types before choosing keys. The companion guide to PROC CONTENTS dataset descriptors explains that inspection task. If the data originate in a text file, resolve import and type issues through the PROC IMPORT workflow before interpreting a surprising sort order. PROC SORT reorders the values it receives; it does not decide what an identifier or visit should mean.
Install or access
The examples use ordinary SAS datasets and the PROC SORT syntax in the Base SAS 9.4 Procedures Guide, Seventh Edition. They concern sorting by SAS with the Base SAS engine, rather than an assumed ordering of database query results or a CAS distributed table. Use your institution’s SAS environment for its approved research workflow.
For learning the commands, SAS also provides SAS OnDemand for Academics through SAS Studio. Its official support page describes access for independent learners, students and instructors, with an Independent Learners route to registration. Use the fictional data supplied here to practise. The service’s availability for learning should not be read as permission to upload an institution’s research files.
The task below is expressed as a program, so it does not depend on a particular menu layout. Keep the complete DATA and PROC steps together, including their terminating semicolons and RUN statements. Explicit input and output names make it possible to trace which file each later step reads.
Step-by-step task: SAS PROC SORT with a worked example
This illustrative composite contains invented participant identifiers and scores, not research findings. The row_id variable identifies the original record independently of participant and visit. That extra identifier makes record retention visible when two observations share an analytical key.
- Create the example input. The five rows deliberately include two records for participant 101 at visit 2, with different scores. Keep this difference in view: equal keys do not establish that the complete observations are identical.
data work.visits;
input row_id participant visit score;
datalines;
1 102 2 18
2 101 2 14
3 101 1 12
4 102 1 16
5 101 2 15
;
run;
- Sort without replacing the input. DATA= names the source; OUT= names a different result. The required BY statement orders participant first and visit within participant. Ascending order is the default for both keys.
proc sort data=work.visits out=work.visits_sorted equals;
by participant visit;
run;
The documented EQUALS option preserves the input-relative order of observations whose complete BY values tie. Here it makes the relative positions of row 2 and row 5 explicit. It does not choose between their scores, and it does not make the participant-visit key unique.
PROC SORT BY SAS: primary and secondary keys
Read the BY list from left to right. With by participant visit;, all observations for participant 101 come before those for 102. Within 101, visit 1 precedes visit 2. Changing the list to by visit participant; would group all visit-1 observations first and then order participants inside each visit. Both commands are valid, but they answer different ordering tasks.
Specify the key order needed by the next processing step. A visually plausible report is not enough evidence that the file has the required sequence. In particular, sorting by participant first does not create a file globally ordered by visit.
- Reverse only the key that needs it. Place DESCENDING immediately before visit to show later numbered visits first within each participant. Participant remains ascending.
proc sort data=work.visits out=work.visits_latest_first equals;
by participant descending visit;
run;
DESCENDING modifies only the following variable. To reverse both participant and visit, write by descending participant descending visit;. Moving the keyword changes the ordering specification; it is not a global switch for the entire BY list. None of these commands removes a record.
- Display the sorted observations. Use PROC PRINT on the named result rather than expecting PROC SORT to generate a report.
proc print data=work.visits_sorted;
var row_id participant visit score;
run;
Using a separate output name also lets you inspect work.visits and work.visits_sorted independently. Omitting OUT= would allow PROC SORT to replace the input dataset when it completes successfully. Specifying the same name in DATA= and OUT= also replaces that dataset; the protection comes from using a different destination.
Output and how to read it
PROC SORT produces a dataset. A printed table comes from a subsequent reporting procedure, while the SAS log records execution notes. Keep these three objects distinct when checking a program: a dataset can exist even when there is no printed report, and a printed report is not a substitute for checking the procedure’s log.
For the ascending participant-visit example, the expected row_id sequence is 3, 2, 5, 4, 1. Row 3 has participant 101 and visit 1; rows 2 and 5 have participant 101 and visit 2. EQUALS preserves their input-relative order. Rows 4 and 1 then represent participant 102 at visits 1 and 2. All five records remain, and all original scores remain attached to their row identifiers.
For participant ascending and visit descending, the expected sequence is 2, 5, 3, 1, 4. Rows 2 and 5 still tie on both ordering keys. The reverse visit order moves their group ahead of row 3, but does not reverse the tied records within the group.
PROC SORT in SAS: NODUPKEY changes record retention
NODUPKEY writes one observation per complete BY key. It does not compare every variable unless every variable is included in that key. Use a separate DUPOUT= dataset to retain the observations excluded by this operation for inspection.
proc sort data=work.visits_sorted
out=work.visits_one_per_key
dupout=work.visits_repeated_keys
nodupkey equals;
by participant visit;
run;
proc print data=work.visits_one_per_key;
var row_id participant visit score;
run;
proc print data=work.visits_repeated_keys;
var row_id participant visit score;
run;
Under the Base SAS engine and SAS sorting behavior described above, retained row identifiers are 3, 2, 4, 1, and the excluded record is 5. The retained score for participant 101 at visit 2 is therefore 14, not 15. This is a consequence of input-relative order and the chosen key; it is not a rule that 14 is more accurate, earlier in time, or analytically preferable.
A retention rule such as choosing a most recent submission needs a defined ordering variable and an explicit tie policy. EQUALS alone supplies neither a timestamp nor a quality judgment. SAS also warns that unpredictable database retrieval order can prevent repeatable retention even when EQUALS is requested. Do not extend the local-dataset result to an unspecified database or host-sort environment.
The downloadable data table below compiles the separate ordering, replacement and retention consequences of the relevant directives. It is a reference to documented behavior, not a table of observed performance measurements. For a later check of paired data versions, the PROC COMPARE guide covers dataset comparison as a separate task.
Troubleshooting
No printed results after a successful sort
Check whether the program contains a reporting step. The SORT procedure itself creates only a dataset; use PROC PRINT with DATA= pointing at the output you intend to inspect. Reading a previously created dataset can make an otherwise correct new sort appear to have done nothing.
Records disappeared after adding NODUPKEY
Inspect the entire BY list and the DUPOUT= dataset. With by participant;, every additional observation for that participant shares the key, even when its visit and score differ. With by participant visit;, the retention unit is the participant-visit pair. Neither command establishes whether the removed observation was erroneous.
Sorting by all variables with NODUPKEY instead defines complete-observation uniqueness. In this example, row_id differs on every record, so all five complete observations are distinct. An audit identifier can therefore change the answer to a whole-row uniqueness check. Decide which variables define the research record before translating that definition into syntax.
Missing or character values appear in an unexpected position
SAS numeric missing values precede negative numbers, zero and positive numbers in ascending order. A missing numeric value at the beginning of a group is therefore consistent with the documented order. DESCENDING reverses the direction for its following variable. Inspect the values and types rather than treating a missing value as an ordinary zero.
Character ordering depends on the session encoding and collating sequence. Do not assume that differently cased text or numeric-looking character identifiers will follow the same rules as numeric variables. The manual documents collation options, but the examples here deliberately use numeric keys and make no cross-locale text-order guarantee.
The wrong duplicate-related option was selected
NOUNIQUEKEY and NODUPKEY answer different questions. NODUPKEY retains one record per key. NOUNIQUEKEY removes singleton key groups and retains every observation in groups with repeated keys; it is useful for inspecting repeated groups rather than producing one record per group. SAS documents the two options as incompatible in the same step.
Before accepting a prepared dataset, check the input and output names, the BY variables in order, the placement of every DESCENDING keyword, and whether any retention option was requested. Then reconcile the record count and inspect the tied keys. If the next task is reshaping repeated observations, the PROC TRANSPOSE workflow explains that distinct operation.
Free alternatives
R and pandas provide freely available alternatives for ordering tabular records. Their official documentation describes their own functions and defaults; changing software does not by itself preserve SAS’s treatment of missing values, text collation or record retention. The table compares basic ordering tasks, rather than claiming an exact translation of the entire procedure.
| Tool | Documented ordering approach | Difference to check |
|---|---|---|
| R, base package | Use order(participant, visit) to obtain ordering indices, then subset the dataframe’s rows with those indices. | order returns indices rather than directly replacing the dataframe. Its na.last argument defaults to TRUE, placing missing values last. |
| Python with pandas | Use DataFrame.sort_values with the relevant column names in by and an ascending value or list for the directions. | The na_position default is ‘last’. Ordering with sort_values is a separate operation from deciding which repeated keys to retain. |
For either alternative, first specify the same intended keys and directions in ordinary language. Then compare actual row identifiers after ordering, especially where keys tie or contain missing values. That comparison is more informative than checking only the first few displayed values, because different records can share the same visible key.
Sources
- SAS Institute: Base SAS 9.4 Procedures Guide, Seventh Edition, SORT chapter, including PROC SORT statement, BY statement, results and examples. Checked 2026-11-16.
- SAS OnlineTutor: SORT Procedure. Checked 2026-11-16.
- SAS Support: SAS OnDemand for Academics. Checked 2026-11-16.
- R Project: What is R?. Checked 2026-11-16.
- R base documentation: Ordering Permutation. Checked 2026-11-16.
- pandas project: About pandas. Checked 2026-11-16.
- pandas API reference: DataFrame.sort_values. Checked 2026-11-16.
Data: PROC SORT directives: ordering, replacement and retention
Original compilation of selected PROC SORT directives by their effect on ordering, input replacement and record retention. Compiled from the SAS Institute Base SAS 9.4 Procedures Guide, Seventh Edition; page references identify the supporting sections. These are documented behaviors for ordinary SAS datasets, not measured runtime results.
| Directive | Purpose | Effect or condition to inspect | SAS manual printed pages |
|---|---|---|---|
| OUT= with a different dataset name | Create a separate sorted result | Preserves input; omitting OUT= or naming the input again allows replacement. | 2424–2425; 2435 |
| BY variable list | Define ordered keys | Ascending by default; each later variable orders ties on preceding variables. Does not itself remove observations. | 2429; 2422 |
| DESCENDING before a BY variable | Reverse one key direction | Affects only the immediately following variable, not the complete BY list. | 2429 |
| NODUPKEY | Retain one observation per complete BY key | Different non-key values can be excluded; complete-row uniqueness requires all variables in the key. | 2422–2423 |
| EQUALS | Preserve input-relative order of tied BY values | Supports predictable first-record retention for Base SAS engine input sorted by SAS; cannot cure unpredictable database retrieval. | 2421–2423; 2426 |
| DUPOUT= with NODUPKEY | Save excluded duplicate-key observations | Provides a separate dataset for observations removed by the duplicate-key operation. | 2420–2421; 2424 |
Sources
- SAS Institute: Base SAS 9.4 Procedures Guide, Seventh Edition, SORT Procedure (accessed 2026-11-16)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







