Skip to main content
v2026.11,986 entries · CC-BY 4.0

SAS Substring: SUBSTR Syntax, Examples and Errors

How to take a substring in SAS with SUBSTR: syntax, extraction and replacement examples, error handling, and when to use SUBSTRN, SCAN or %SUBSTR.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

The SAS substring function is SUBSTR. Written on the right of an equals sign, variable = SUBSTR(string, position, length) returns the part of a character string that starts at position and runs for length characters; if you leave out length, it returns everything from position to the end of the string. Written on the left of an equals sign, SUBSTR(variable, position, length) = text instead replaces part of an existing variable. This page covers both forms, the related SUBSTRN, %SUBSTR and SCAN tools, what happens when an argument is out of range, and how to fix the common errors. It is based on the SAS 9 documentation; read it as a SAS 9 reference.

What it is used for in research

Research data often arrives with meaning packed into fixed positions of a text field: a date such as 06MAY98, a site code at the start of a participant identifier, a specimen code whose last two characters are a batch number, or a diagnosis code whose first characters give the category. Pulling those pieces out into their own variables is the job of a substring function. In a SAS analysis this usually happens in a DATA step, before the cleaned variables go into PROC steps for tabulation or modelling.

SAS documents SUBSTR in two roles that behave differently, plus a macro-language version, and it is worth keeping them apart from the start:

  • Extraction (right of the equals sign). Copies a portion of a string into a variable. This is what most people mean by “substring in SAS”.
  • Replacement (left of the equals sign). Overwrites characters inside an existing character variable. The documented example turns KIDNAP into CATNAP.
  • Macro substring (%SUBSTR). Works on macro text during macro processing, not on data values in a DATA step.

For delimited text such as smith;jane;1984 there is usually no fixed position to count to, and SCAN is the better tool; the decision table later on this page sets out when to use which. If your input may contain positions or lengths that fall outside the string, the companion page SAS SUBSTRN function explains the variant that tolerates them.

How to install or access it

SUBSTR is part of the SAS programming language, so nothing extra has to be installed: if you can run a DATA step, you can use it. SAS Institute lists the function in the SAS 9 language reference at support.sas.com, and the syntax on this page follows that documentation.

If you do not have a licensed SAS installation through your institution, SAS offers a free browser-based route, SAS OnDemand for Academics. SAS describes it as a free, cloud-based learning environment. SAS Studio, the browser interface for writing and running SAS programs, is available to anyone who registers, including independent learners who are not affiliated with a school; students on a registered course receive a code from their instructor. SAS states a storage allowance of up to 5GB of data per user. Check the terms of use on the SAS site before relying on it for anything beyond learning. For SAS in general, see the overview in SAS for academic users and the broader coding in SAS guide.

Step-by-step task: extract and replace a substring in a DATA step

These steps use only the syntax and behaviour given in the SAS documentation. Run them in SAS Studio or any SAS session.

Substring in SAS: extract part of a character value

  1. Identify the character variable and count the position of the first character you want. Positions start at 1.
  2. Decide how many characters to take. If you want everything from that position to the end, you can omit the length.
  3. Write the assignment with the new variable on the left and the function on the right: variable = SUBSTR(string, position, length);
  4. Run the DATA step and check the new variable in the output or with a PUT statement.

The SAS documentation example uses a date stored as 06MAY98:

data _null_;    date='06MAY98';    month=substr(date,3,3);    year=substr(date,6,2);    put @1 month @5 year; run;

The documented result is MAY 98: starting at position 3 and taking 3 characters gives MAY, and starting at position 6 and taking 2 gives 98. Because the first argument is a character variable, the new variables take their length from it unless you have declared a length earlier (see the troubleshooting section for why this matters).

SAS substring function on the left side: replace characters

  1. Make sure the target is a character variable that already exists, or give it a length first. SAS documents that an undeclared variable gets a default length of 8 at compile time.
  2. Write the function on the left of the equals sign with the replacement text on the right: SUBSTR(variable, position, length) = characters-to-replace;
  3. Keep the length within what remains after position; the documentation says the length cannot exceed the remaining length. If you omit it, SAS uses all the characters on the right side of the equals sign.

The documented examples:

a='KIDNAP'; substr(a,1,3)='CAT'; put a;        /* CATNAP */ b=a; substr(b,4)='TY'; put b;        /* CATTY */

In the second example the length is omitted, so all of the right-hand text, TY, is written starting at position 4, turning CATNAP into CATTY.

Substring in a macro: %SUBSTR and %QSUBSTR

In the macro language the form is %SUBSTR(argument, position, length), and omitting length returns text to the end of the argument. A typical use is trimming a macro variable: %let fileref = %substr(&fileref,1,8); keeps the first eight characters. If the position is beyond the end of the text, SAS issues a warning and returns a null value; if the length is too large it issues a warning and returns the characters to the end. %SUBSTR does not mask special characters such as & and %, so text that contains them gets resolved. Use %QSUBSTR when you want the characters returned as literal text. The SAS documentation shows this with %let c=%nrstr(&a &b);: %substr(&c,1,2) tries to resolve the &a reference, while %qsubstr(&c,1,2) returns &a as text.

SAS substring function for delimited text: SCAN

When the part you want is the Nth word rather than characters at known positions, use SCAN(string, count, charlist, modifiers). A negative count scans from right to left, so -1 returns the last word. By default, SCAN treats a blank and the characters ! $ % & ( ) * + , - . / ; < ^ | as delimiters (ASCII systems). Supply the charlist argument when you want only specific delimiters. The documented modifiers are M, Q, K and D; the SCAN reference page describes each.

Output and how to read it

A DATA step substring produces a new character variable, so read the result the way you would any character field: check its length, look for trailing blanks, and print a few observations to confirm that the positions you counted are the ones you intended. A PUT statement writes values to the log, which is the quickest check for the documented examples above.

The log is also where SAS reports a problem with the arguments. If SUBSTR receives a length that is zero, negative, or larger than the characters remaining, the documentation states that it returns the remainder of the string from position, writes a note about an invalid length argument to the log, and sets the automatic variable _ERROR_ to 1. The step still runs, which means a bad length can produce plausible-looking but wrong values. Read the log after any step that uses SUBSTR on real data.

What happens at the edges

The table below compares how the functions documented in the SAS 9 language reference treat out-of-range arguments. Every row is taken from the cited reference page.

Function Position or length outside the string Where you see it
SUBSTR (right side) Length of zero, negative, or beyond the end: returns the remainder from position Log note, _ERROR_=1
SUBSTRN Non-positive position starts at the first character, with the result shortened; non-positive length returns a zero-length result; past the end is truncated No error note
%SUBSTR Position beyond the string returns a null value; length beyond the string returns characters to the end Warning
SCAN Count beyond the number of words returns a single blank in a DATA step No error note

Troubleshooting

The result is cut short

In a DATA step, a new receiving variable that has no earlier length takes the length of the first argument of SUBSTR. If a later observation needs more characters than the first definition allowed, set the length yourself with a LENGTH statement before the assignment. For SCAN, the documented default result length in a DATA step is 200 characters.

The log shows an invalid length argument note

This is the documented signal that the length was zero, negative, or longer than the remaining characters, and that _ERROR_ is now 1. Check how the length is calculated, especially if it comes from another variable that can be missing or zero. If out-of-range values are expected in your data, SUBSTRN handles them without the note.

Replacement does nothing or truncates

The left-side form needs a character variable, and its length cannot exceed the remaining length after position. An undeclared variable receives a default length of 8, so declare the variable with a sufficient length first.

A macro variable loses its ampersand or percent sign

Switch from %SUBSTR to %QSUBSTR, which returns special characters as text rather than resolving them.

SCAN returns a blank

If the count is larger than the number of words, SCAN returns a single blank in a DATA step. Count the words first, or use a negative count such as -1 when you always want the last word.

Choosing between SUBSTR, SUBSTRN, SCAN and %SUBSTR

Your data looks like Use Why (per SAS documentation)
Fixed positions, valid lengths SUBSTR Extracts from position for length, or to the end if length is omitted
Fixed positions, but arguments may be zero, negative or too large SUBSTRN Returns a shortened or zero-length result instead of an error note
Words separated by delimiters SCAN Counts words, and a negative count scans from the right
Text held in a macro variable %SUBSTR or %QSUBSTR %QSUBSTR keeps & and % as literal characters
Changing characters inside an existing variable SUBSTR on the left Overwrites in place; length must fit the remainder

SUBSTRN also accepts a numeric first argument, which SAS converts using BEST32. first; the documented example is SUBSTRN(1234.5678,2,6), which returns 234.56.

For a character-set note, SAS records that SUBSTR is for single-byte data and points users working with double-byte character sets to KSUBSTR and KSUBSTRB in its national language support reference.

Free alternatives

Option What it gives you Source or CASRAI page
SAS OnDemand for Academics (SAS Studio) Free, cloud-based SAS programming in a browser, so you can run SUBSTR without an institutional licence; up to 5GB of data per user SAS, sas.com (read 2026-11-12)
R with the stringr package String extraction in a free, open statistical environment; not SAS syntax stringr cheat sheet
Other no-cost statistics tools Overview of free statistical software for researchers free statistical software, R explained

The data table below compares the SAS string functions covered here, with each syntax and the behaviour of omitted lengths taken from the SAS documentation pages listed under Sources.

FAQ

What is the substring function in SAS?

It is SUBSTR. On the right of an equals sign, SUBSTR(string, position, length) extracts characters; omit the length to take everything from the position to the end.

How do I do a substring in SAS from the right end of a string?

SUBSTR counts from the left, so you need a position that you work out yourself, for example from the string length. For delimited text, SCAN with a count of -1 returns the last word without counting characters.

Can SUBSTR change a value as well as read one?

Yes. On the left of the equals sign it replaces characters in place; the documented example changes KIDNAP to CATNAP.

What is the difference between SUBSTR and SUBSTRN?

With an out-of-range length, SUBSTR returns the remainder, writes a log note and sets _ERROR_ to 1, while SUBSTRN returns a shortened or zero-length result. See the SUBSTRN guide.

Does the SAS substring function work in macro code?

The macro language has its own %SUBSTR, and %QSUBSTR when special characters must be kept as text.

Where does this fit in a wider SAS workflow?

String clean-up is one early step in preparing data for analysis. Other SAS topics on CASRAI include date formats in SAS and PROC CONTENTS for checking variable lengths and types.

Sources

  • SAS Institute, SUBSTR function (right of the equals sign), SAS 9 Language Dictionary: support.sas.com, read 2026-11-12.
  • SAS Institute, SUBSTR function (left of the equals sign), SAS 9.3 Functions and CALL Routines Reference: support.sas.com, read 2026-11-12.
  • SAS Institute, SUBSTRN function: support.sas.com, read 2026-11-12.
  • SAS Institute, %SUBSTR function, SAS Macro Language Reference: support.sas.com, read 2026-11-12.
  • SAS Institute, SCAN function: support.sas.com, read 2026-11-12.
  • SAS Institute, SAS OnDemand for Academics: sas.com, read 2026-11-12.

Data: SAS 9 string-extraction functions: syntax and handling of omitted or out-of-range arguments

Compares SUBSTR (extraction and replacement), SUBSTRN, %SUBSTR and SCAN as described in the SAS 9 documentation, compiled from the vendor's function reference pages: syntax, what an omitted length does, and what happens with out-of-range arguments.

SAS 9 string-extraction functions: syntax and handling of omitted or out-of-range arguments
FunctionSyntaxOmitted length or defaultOut-of-range behaviour
SUBSTR (right of =)variable=SUBSTR(string, position)Remainder of the string from positionLength zero, negative or too large returns the remainder, sets _ERROR_=1 and writes a log note
SUBSTR (left of =)SUBSTR(variable, position)=characters-to-replaceUses all characters on the right side of the equals signLength cannot exceed the remaining length after position; undeclared variable gets default length 8
SUBSTRNSUBSTRN(string, position)Remainder of the string from positionNon-positive position starts at first character (shortened); non-positive length gives zero-length result; past end is truncated
%SUBSTR%SUBSTR(argument, position)Text to the end of the argumentPosition beyond string: warning and null value; length beyond string: warning and characters to the end
SCANSCAN(string, count)Default delimiters are blank and ! $ % & ( ) * + , - . / ; < ^ |; default DATA step result length 200Count beyond the number of words returns a single blank in a DATA step; negative count scans right to left

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about SAS Substring: SUBSTR Syntax, Examples and Errors

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →