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

INDEX Function in SAS: Syntax, Examples and Common Errors

How SAS INDEX(source, excerpt) returns the first match position or 0, with worked examples, the trailing-blank trap and INDEXC, INDEXW and FIND compared.

Written and maintained by CASRAI Editorial Board

Published

On this page

The INDEX function in SAS searches a character value from left to right and returns the position of the first character of the first match, or 0 when the text is not found. Its syntax is INDEX(source, excerpt): source is the text to search and excerpt is the string to look for. It is the standard way to ask “does this character variable contain this text, and where?” inside a DATA step.

What the INDEX function is used for in research

Research datasets often hold free text or semi-structured codes: affiliation strings, adverse-event descriptions, drug names, free-text survey answers, file paths, diagnosis text. INDEX lets you flag or extract records by their content without writing a pattern language. Typical research uses are:

  • Flagging records whose text contains a keyword, for example every adverse-event description that mentions a given term.
  • Locating a delimiter, such as a hyphen or an equals sign, so that the part before or after it can be pulled out with a substring function (see SAS substring for the related functions).
  • Screening variable names or labels for a stem when cleaning a dataset.
  • Subsetting observations with a condition of the form index(var, 'text') > 0.

INDEX is one of four related search functions (INDEX, INDEXC, INDEXW and FIND). Picking the right one is the main decision, and the comparison table later on this page sets them side by side.

How to install or access the INDEX function

INDEX is not a separate package or procedure: it is a function of the SAS programming language, so you use it in any SAS session that runs a DATA step. Access to SAS itself comes through the licence your institution or organisation holds; the function reference that this page follows is the SAS 9.3 Functions and CALL Routines Reference on support.sas.com. For background on the software, see CASRAI’s guides to coding in SAS and SAS for academic use.

Two points from the reference are worth knowing before you start. INDEX is a character function for single-byte character sets; the double-byte counterpart is KINDEX. And a different function with a similar name exists in the SAS macro language (%INDEX), which works on macro text and is not the DATA step function described here.

How to use the INDEX function step by step

  1. Identify the character variable (the source). This can be a character variable, a quoted character constant or a character expression.
  2. Decide on the excerpt. Quote literal text, for example 'data', or pass a character variable. Both arguments are required.
  3. Call the function in a DATA step. Assign the result to a numeric variable: pos = index(title, 'data');
  4. Handle blanks deliberately. Leading and trailing blanks in the excerpt are part of the search string. If the excerpt sits in a fixed-length variable, wrap it in TRIM so the padding blanks are ignored: pos = index(title, trim(term));
  5. Use the result. A value greater than 0 means a match; 0 means no match. For example, to keep only matching records: if index(title, 'data') > 0;

A complete example that creates a flag and extracts the text before a delimiter:

data work.flagged;
  set work.records;
  pos = index(title, 'data');
  has_data = (pos > 0);
  dash = index(title, '-');
  if dash > 0 then stem = substr(title, 1, dash - 1);
run;

The SUBSTR call here is the general substring function; CASRAI’s SAS substring guide and SUBSTRN guide cover the extraction side in detail.

How to read the output

INDEX returns a number, not text. The number is the character position, counting from 1, of the first character of the first match. The reference states that later matches are ignored: only the first occurrence is reported. The table below works through calls using the documented rules.

Call Result Why
index('ABC.DEF(X=Y)', 'X=Y') 9 The match starts at the ninth character (SAS documentation, Example 1).
index('Methods of data analysis', 'data') 12 “Methods of ” is 11 characters, so the match starts at position 12.
index('banana', 'an') 2 Two matches exist, at positions 2 and 4; only the first is returned.
index('banana', 'xyz') 0 No match returns 0.

The first row is taken from the SAS documentation; the other three follow from the documented behaviour (left-to-right search, first match, 0 when absent).

The trailing-blank trap

The most common surprise comes from fixed-length character variables. SAS pads a character variable with blanks to its defined length, and INDEX treats the excerpt’s trailing blanks as part of the search string. The documentation’s own Example 2 shows this: the text X=Y stored in a 14-character variable returns 0 when passed directly, because the search string is really “X=Y” followed by padding blanks. Passing trim(variable) returns 10, the position where X=Y begins in the searched text. When INDEX returns 0 and you can see the text in the data, check for padding first.

Case

INDEX takes only two arguments, so it has no option to ignore case. A ListenData tutorial describes INDEX as case-sensitive and shows normalising with LOWCASE before searching. If you need to ignore case without changing the variable, the FIND function has an i modifier (see below). In either case, test on a few known records before running a whole dataset.

INDEX, INDEXC, INDEXW and FIND compared

Function What it searches for Not found Documented example
INDEX(source, excerpt) A string, as a literal run of characters 0 X=Y in ABC.DEF(X=Y) returns 9
INDEXC(source, excerpt-1, …, excerpt-n) The first position of any single character found in any of the excerpts 0 'have a good day' with 'pleasant' and 'very' returns 2
INDEXW(source, excerpt, delimiters) A whole word, bounded by delimiters (blank by default) or the start or end of the source 0 'dog' in 'asdf adog dog' returns 11
FIND(string, substring, modifiers, startpos) A string, with optional i (ignore case) and t (trim trailing blanks) modifiers and an optional start position 0 With the i modifier, ‘she ‘ in ‘She sells seashells? Yes, she does.’ returns 1; without it, 27

INDEXC: any character from a list

INDEXC does not look for a string; it looks for the first position at which any character from any excerpt appears. In the documentation’s example, searching 'ABC.DEP (X2=Y1)' for any of the digits '0123' and the punctuation ';()=.' returns 4, the position of the period. This makes it the right choice for locating “the first digit” or “the first punctuation mark”.

INDEXW: whole words only

INDEX would find 'dog' inside 'adog'; INDEXW will not. The match must begin and end on a word boundary: a delimiter, the start of the source or the end of the source. With 'dog' searched in 'asdf adog dog', INDEXW returns 11, skipping the embedded “dog” in “adog”. If you supply a custom delimiters argument, the end of the text is no longer treated as a boundary, and trailing blanks in the excerpt matter when the delimiter is not a blank. Searching 'def' in 'abcdef x=y' returns 0 because the match is not on a boundary.

FIND: modifiers and a start position

FIND is the closest relative of INDEX and the one to choose when you need case-insensitive matching or need to start partway along the string. Without the i modifier FIND is case-sensitive. A positive startpos searches rightwards from that position; a negative startpos searches leftwards; a startpos of 0 returns 0.

Troubleshooting the INDEX function

  • It returns 0 but the text is visibly there. The usual cause is trailing blanks in the excerpt variable. Wrap the excerpt in TRIM. Also check that case matches.
  • It only finds the first match. This is by design. To locate later occurrences, search a shorter portion of the string with a substring function, or use FIND with a start position.
  • It matches inside longer words. Use INDEXW when the match must be a complete word.
  • The result is used as a flag but is not 0 or 1. INDEX returns a position. Test with > 0 rather than treating the value as a true/false flag, or build a flag with (index(...) > 0).
  • Searching text in a double-byte character set. INDEX is a single-byte function; the reference points to KINDEX for double-byte data.
  • “Index in SAS” means something else. Searches for “index in SAS” also reach dataset indexes (a data-access structure) and the macro %INDEX function. Neither is the DATA step INDEX function covered here.

Alternatives to the INDEX function

All of these are SAS functions, so they need no additional software. The table lists when each is the better fit, using the behaviours documented above.

Need Use Reason (from the reference)
Case-insensitive search FIND with the i modifier INDEX has no modifier argument; FIND’s i modifier ignores case
Ignore trailing blanks without TRIM FIND with the t modifier The t modifier trims trailing blanks from both arguments
Start the search part-way along, or search right to left FIND with startpos Positive startpos searches right; negative searches left
First position of any of several characters INDEXC Returns the first position of any character in any excerpt
Whole-word match INDEXW The match must begin and end on a delimiter, start or end of the source
Double-byte character data KINDEX INDEX is for single-byte character sets

For R users weighing the wider move between tools, see the R vs SAS comparison. The data table below lists the documented example calls and returned values for all four functions.

Frequently asked questions

What does the INDEX function do in SAS?

It searches a character value from left to right and returns the position of the first character of the first match of the excerpt, or 0 if there is no match (SAS 9.3 Functions and CALL Routines Reference).

What is the difference between FIND and INDEX in SAS?

Both return the position of the first match. INDEX takes only a source and an excerpt. FIND adds an optional i modifier to ignore case, a t modifier to trim trailing blanks, and an optional starting position that can also search right to left.

How do I make INDEX ignore trailing blanks?

Wrap the excerpt in TRIM, for example index(title, trim(term)). The documentation’s Example 2 returns 0 without TRIM and 10 with it.

Sources

Data: Documented example calls and results for the SAS INDEX, INDEXC, INDEXW and FIND functions

Example calls and returned positions taken from the SAS 9.3 Functions and CALL Routines Reference pages for four string-search functions, compiled into one table so the functions can be compared on identical terms.

Period covered: SAS 9.3 reference.

Documented example calls and results for the SAS INDEX, INDEXC, INDEXW and FIND functions
FunctionCallResult (character position (0 = not found))
INDEXindex('ABC.DEF(X=Y)', 'X=Y')9
INDEXX=Y stored in a 14-character variable, no TRIM0
INDEXtrim(variable) holding X=Y10
INDEXCindexc('ABC.DEP (X2=Y1)', '0123', ';()=.')4
INDEXCindexc('have a good day', 'pleasant', 'very')2
INDEXWindexw('asdf adog dog', 'dog')11
INDEXWindexw('abcdef x=y', 'def')0
FINDfind('She sells seashells? Yes, she does.', 'she ')27
FINDsame call with modifier 'i'1

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 · full access

Ask about INDEX Function in SAS: Syntax, Examples and Common Errors

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

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 →