2.1 SAS Environment, Syntax Rules, & Data Step Basics
Key Takeaways
- Every SAS statement must terminate with a semicolon (;), and SAS syntax is free-format and case-insensitive except within quoted string literals.
- A SAS program is composed of two fundamental step types: DATA steps (for data creation, processing, and transformation) and PROC steps (for statistical analysis, reporting, and file management).
- The compilation phase checks syntax, creates the descriptor portion of the dataset, builds the Program Data Vector (PDV), and initializes automatic variables _N_ and _ERROR_.
- The execution phase runs iteratively for each observation: non-retained variables are reset to missing, raw data is read into the PDV, statements execute, and an implicit OUTPUT and RETURN occur at the end of the DATA step.
- Global statements (e.g., OPTIONS, TITLE, FOOTNOTE, LIBNAME) execute immediately upon compilation and remain active across subsequent DATA and PROC steps until explicitly changed.
2.1 SAS Environment, Syntax Rules, & Data Step Basics
The SAS (Statistical Analysis System) programming architecture relies on a structured, procedural execution environment. Understanding how SAS interprets, compiles, and executes code is essential for passing the SAS Certified Specialist: Base Programming exam (A00-231) and for writing efficient data processing pipelines.
1. Structure of a SAS Program
A complete SAS program consists of one or more building blocks called steps. There are only two types of steps in SAS:
- DATA Steps: Primarily used to read, manipulate, combine, transform, and create SAS datasets. A DATA step begins with a
DATAstatement and typically ends with aRUN;statement. - PROC Steps: Pre-written procedures used to analyze data, calculate statistics, generate reports, and manage SAS files. A PROC step begins with a
PROCstatement and ends with aRUN;(orQUIT;for interactive procedures likePROC REGorPROC SQL).
/* Example of a standard SAS Program with DATA and PROC steps */
/* 1. DATA Step: Data Ingestion and Transformation */
data work.employees_clean;
set work.employees_raw;
if status = 'Active';
annual_salary = monthly_pay * 12;
run;
/* 2. PROC Step: Data Analysis and Reporting */
proc means data=work.employees_clean mean min max;
var annual_salary;
class department;
run;
2. Fundamental Syntax Rules
SAS follows strict rules for program statements, names, and code formatting:
| Rule Category | Description & Exam Nuance |
|---|---|
| Semicolon Termination | Every SAS statement must end with a semicolon (;). A single line of code can contain multiple statements, or a single statement can span multiple lines. |
| Case Sensitivity | SAS code keywords, variable names, and dataset names are case-insensitive (DATA, Data, and data are identical). However, text inside quotes (string literals) is strictly case-sensitive ('Active' $\ne$ 'ACTIVE'). |
| Free-Format Code | Statements can begin in any column, span multiple lines, and contain any amount of whitespace. |
| SAS Names | Variable names and dataset names must be 1 to 32 characters long, begin with a letter or underscore (_), and contain only letters, numbers, or underscores. No special characters or spaces are allowed. |
| Comments | SAS supports two comment formats: block comments (/* comment */) which can span multiple lines and appear anywhere, and statement comments (* comment ;) which must begin with an asterisk and end with a semicolon. |
/* Block comment spanning multiple lines */
* Statement comment ending with a semicolon ;
data work.example; /* Valid inline block comment */
format hire_date mmddyy10. ;
input id name $ salary ;
run;
3. Global SAS Statements
Global statements provide instructions to the SAS system and remain in effect across step boundaries until modified or reset. Unlike step statements, global statements do not belong to a specific DATA or PROC step and take effect immediately when SAS parses them.
Common global statements include:
OPTIONS: Sets system control parameters (e.g.,options nodate pageno=1 linesize=80;).TITLE/FOOTNOTE: Defines headers and footers for printed report output (e.g.,title1 "Q3 Financial Report";). Titles range fromTITLE(orTITLE1) toTITLE10.LIBNAME: Assigns a logical library reference (libref) to a physical directory.FILENAME: Assigns a logical file reference (fileref) to an external file or storage location.
Exam Tip: Executing a
TITLEstatement replaces the title at that specific line number and clears all higher-numbered titles. For example, issuingtitle1 "New Title";automatically suppresses any previously definedtitle2throughtitle10.
4. The SAS Data Step Processing Cycle: Compilation vs. Execution
The most tested concept on the SAS Base exam is the internal mechanism of DATA step processing. SAS processes a DATA step in two distinct phases: Compilation and Execution.
+-----------------------------------------------------------------------+
| COMPILATION PHASE |
| 1. Syntax Check 2. Create Input Buffer 3. Build PDV 4. Header File |
+-----------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------+
| EXECUTION PHASE |
| 1. Initialize PDV 2. Read Observation 3. Process Logic |
| 4. Implicit OUTPUT 5. Implicit RETURN (Loop back to step 1) |
+-----------------------------------------------------------------------+
Phase 1: Compilation
During compilation, SAS reads the code line-by-line to check for syntax errors and establishes the dataset structure before reading any data rows:
- Syntax Checking: Scans for missing semicolons, invalid keywords, and mismatched quotes.
- Creation of the Program Data Vector (PDV): SAS constructs a temporary memory structure called the PDV. The PDV contains memory slots for every variable referenced in the DATA step.
- Automatic Variables: SAS automatically creates two invisible variables in the PDV:
_N_: Tracks the number of times the DATA step has iterated (starts at 1)._ERROR_: Serves as a binary error flag (0 = no error, 1 = execution error occurred).
- Descriptor Portion Creation: SAS determines variable names, types (character or numeric), lengths, informats, formats, and labels, establishing the header of the target output dataset.
Phase 2: Execution
Once compilation completes cleanly, SAS enters execution mode. The DATA step executes in an implicit iterative loop (once per input observation):
- Initialization: All non-retained variables in the PDV are set to missing (
.for numeric, blank' 'for character)._N_is set to the current iteration count. - Data Ingestion: An input record is read into the PDV (from an
INFILEbuffer or an existing SAS dataset specified in aSETstatement). - Statement Execution: SAS processes programming statements (assignments,
IF-THEN/ELSEconditions, functions) sequentially from top to bottom. - Implicit OUTPUT: When SAS reaches the end of the DATA step (the
RUN;boundary), it automatically writes the current contents of the PDV to the output dataset. - Implicit RETURN: Execution returns to the top of the DATA step to begin the next iteration until the end-of-file (EOF) marker is reached.
/* Demonstrating PDV execution behavior */
data work.sales_summary;
set work.raw_transactions;
/* _N_ increments automatically on each iteration */
total_cost = quantity * unit_price;
/* At RUN statement: implicit OUTPUT occurs, then implicit RETURN */
run;
5. Common Pitfalls & Exam Watchouts
- Missing Semicolons: A missing semicolon causes SAS to interpret the next line as a continuation of the previous statement, generating misleading syntax error messages.
- Variable Length Assignment: A variable's length and type are fixed by its first appearance during compilation. If a variable is assigned a 4-character string first, subsequent assignments of longer strings will be truncated to 4 characters unless a
LENGTHstatement precedes it. - Case Sensitivity in Character Comparison:
if state = 'nc'will return false if the dataset contains'NC'or'Nc'. Use theUPCASE()orLOWCASE()function for case-insensitive filtering.
Which phase of DATA step processing is responsible for establishing the Program Data Vector (PDV) and creating the descriptor portion of the output dataset?
Consider the following SAS code snippet: proc print data=work.employees; title1 "Active Personnel Report"; title2 "Confidential"; run; title1 "Department Summary"; proc print data=work.departments; run; What title(s) will appear at the top of the output for the second PROC PRINT step?
A programmer writes the following SAS DATA step to filter sales transactions:
data work.high_value;
set work.all_sales;
if Region = 'east' then output;
run;
If the dataset work.all_sales contains values of 'EAST', 'East', and 'east' for the variable Region, how many of these variations will be selected?
During the execution phase of a standard DATA step reading an input dataset with a SET statement, what happens to non-retained variables in the Program Data Vector (PDV) at the start of each iteration?