7.2 Syntax vs. Logic Errors & Phasing

Key Takeaways

  • Syntax errors represent violations of SAS grammar rules detected during the Compilation Phase, preventing DATA step execution or placing SAS into syntax-check mode.
  • Logic errors occur during the Execution Phase when a program runs without SAS error messages but generates incorrect results due to flawed program logic.
  • When SAS detects a compilation syntax error, it writes an ERROR message to the log, flags the error location with a underline/caret marker, and sets OBS=0 syntax-check mode for downstream steps.
  • Unclosed quotation marks trigger the 'quote sticky' condition, causing SAS to parse subsequent program code as literal text until a matching quote and semicolon are parsed.
  • Execution-phase runtime errors include division by zero, mathematical domain violations (e.g. LOG of negative numbers), and missing input datasets.
Last updated: August 2026

7.2 Syntax vs. Logic Errors & Phasing

In SAS programming, errors are broadly classified into two categories based on when and how they manifest: Syntax Errors (detected during the Compilation Phase) and Logic Errors (manifested during the Execution Phase). Distinguishing between compilation syntax failures and runtime logic errors is essential for effective debugging and is a central focus of the SAS Base Programming exam.


1. Compilation Phase vs. Execution Phase Overview

As established in Chapter 1, SAS processes every DATA step in two distinct phases: Compilation (parsing syntax, checking keywords, building the PDV, and creating the dataset header) and Execution (iteratively reading data rows, evaluating expressions, and writing observations).

+-------------------------------------------------------------------------+
|                           COMPILATION PHASE                             |
| Checks Syntax -> Builds PDV -> Creates Descriptor -> Detects SYNTAX ERRORS|
+-------------------------------------------------------------------------+
                                     |
                                     v
+-------------------------------------------------------------------------+
|                            EXECUTION PHASE                              |
| Processes Data Rows -> Evaluates Logic -> Detects RUNTIME/LOGIC ERRORS  |
+-------------------------------------------------------------------------+
AttributeSyntax ErrorsLogic Errors
Phase DetectedCompilation PhaseExecution Phase (or post-execution audit)
Detection MechanismSAS Language Processor / ParserHuman audit, validation checks, or unexpected output
Log IndicatorsERROR: Syntax error... or red error messagesClean log with NOTE: The data set WORK.OUT has N observations
Dataset CreationDataset is not created, or created with 0 observationsDataset is created, but contains incorrect data values
Primary CausesMissing semicolons, misspelled keywords, unclosed quotesIncorrect IF conditions, misplaced OUTPUT, wrong BY variables

2. Syntax Errors (Compilation Phase)

Syntax errors occur when program statements violate the grammar rules of the SAS language. Because compilation occurs before any data is processed, syntax errors prevent SAS from executing the step.

A. Common Syntax Error Triggers

  1. Missing Semicolons: Omitting a semicolon causes SAS to merge two independent statements into a single invalid statement.
  2. Misspelled Keywords: Misspelling keywords (e.g., DATA, SET, PROC, WHERE, FORMAT) prevents statement recognition.
  3. Unclosed Quotes ("Quote Sticky Condition"): If a string literal is missing a closing quotation mark, SAS interprets all subsequent program code as part of the string text.
  4. Invalid Variable Names: Using variable names that exceed 32 characters, contain spaces, or start with digits.
/* Example 1: Missing Semicolon leading to Syntax Error */
data work.sales
    set work.raw_sales; /* ERROR: SAS reads 'data work.sales set work.raw_sales;' */
    total = price * quantity;
run;

/* Example 2: The Quote Sticky Condition */
data work.customers;
    set work.raw_cust;
    if region = 'East then region_code = 1; /* Unclosed single quote */
    format account_date date9.;
run;

B. SAS Behavior Upon Compilation Failure

When SAS encounters a syntax error during compilation:

  1. SAS prints an ERROR: message in the log, followed by an underline marker (_) or caret pointing to the exact character position of the error.
  2. SAS attempts syntax recovery to parse remaining statements, but marks the step as un-executable.
  3. Syntax-Check Mode (OBS=0 Mode): In batch or interactive SAS environments, a severe compilation error sets the system option NOEXEC or OBS=0. SAS continues parsing downstream DATA and PROC steps to check for additional syntax errors, but does not process dataset observations or overwrite existing output datasets.
/* Log manifestation of Syntax Error */
24   data work.test;
25       set work.input;
26       total = salary + ;
                          _
                          22
ERROR 22-322: Syntax error, expecting one of the following: a name, a given name, 
              a numeric constant, a datetime constant...

3. Runtime Execution Errors

Runtime errors occur during the Execution Phase. The program successfully passes compilation syntax checks, but encounters invalid mathematical operations or data conditions while processing rows.

Common Execution-Phase Errors include:

  • Division by Zero: pct = revenue / 0; $\rightarrow$ SAS logs a NOTE/ERROR warning: Mathematical operations could not be performed at the places given by..., sets result to missing (.), and sets _ERROR_ = 1.
  • Invalid Mathematical Arguments: log_val = LOG(-10); or sq = SQRT(-4); $\rightarrow$ Results in invalid argument diagnostic notes.
  • Array Subscript Out of Bounds: Referencing arr[5] when an array is dimensioned as array arr[3]. SAS halts the DATA step with a execution error.

4. Logic Errors (Execution Phase Flaws)

A logic error is the most dangerous error type in enterprise SAS programming because SAS generates no errors or warnings in the log. The code is syntactically flawless, but the program produces incorrect results due to flawed algorithm design.

Common Logic Error Scenarios

Scenario A: Misplaced Explicit OUTPUT Statement

When an explicit OUTPUT; statement is included inside a DATA step, SAS overrides the default implicit OUTPUT at the RUN; boundary.

/* LOGIC ERROR: Misplaced OUTPUT statement inside a DO loop */
data work.investment;
    capital = 1000;
    do year = 1 to 5;
        capital = capital * 1.05;
        output; /* Writes 5 observations per input record instead of 1 final summary */
    end;
run;

Scenario B: Overwriting Subsetting Logic with IF-THEN

Using independent IF-THEN statements instead of IF-THEN / ELSE IF can inadvertently overwrite previously assigned categories.

/* LOGIC ERROR: Flawed conditional logic */
data work.tier;
    set work.customers;
    if spent > 10000 then tier = 'Gold';
    if spent > 1000  then tier = 'Silver'; /* Overwrites 'Gold' for spent > 10000! */
run;

/* CORRECT LOGIC: Use ELSE IF */
data work.tier_correct;
    set work.customers;
    if spent > 10000    then tier = 'Gold';
    else if spent > 1000 then tier = 'Silver';
    else                     tier = 'Bronze';
run;

Scenario C: Incorrect Variable Order in PROC SORT before Match-Merging

If two datasets are sorted by BY Region Dept in one dataset and BY Dept Region in the second, a subsequent MERGE statement compiles without error but produces scrambled, invalid merged records.


5. Systematic Troubleshooting Workflow

To diagnose complex SAS program failures, follow this structured troubleshooting sequence:

  1. Check the SAS Log First: Search for red ERROR: lines and yellow WARNING: lines.
  2. Verify Compilation Syntax: Ensure all quotes are matched, semicolons exist, and librefs are assigned.
  3. Inspect Output Metadata (PROC CONTENTS): Verify variable types (character vs numeric) and lengths match expectations.
  4. Audit Intermediate Datasets (PROC PRINT): Print the first 10 observations ((obs=10)) of intermediate datasets to verify calculations prior to final reporting.
Test Your Knowledge

A SAS programmer submits a DATA step containing an unclosed single quote in a text assignment statement. How does SAS handle this situation during compilation?

A
B
C
D
Test Your Knowledge

Which of the following issues represents a LOGIC ERROR rather than a syntax or execution-phase error?

A
B
C
D
Test Your Knowledge

Consider the following SAS DATA step: data work.calc; x = 100; y = 0; z = x / y; run; What happens during execution of line 4?

A
B
C
D
Test Your Knowledge

When SAS encounters a compilation error in a batch execution environment, what is the effect of syntax-check mode (OBS=0 mode) on subsequent steps in the program?

A
B
C
D