How to filter rows that contain string in SAS?

In SAS you can filter rows that contain a string by using the WHERE statement in a PROC SQL query. This statement specifies a condition that the string must meet in order for the row to be included in the output. You can use the LIKE operator to specify a pattern or value that the string needs to match in order to be included in the output. This allows you to easily filter out rows that contain the specific string you are looking for.


You can use the following methods to filter SAS datasets for rows that contain certain strings:

Method 1: Filter Rows that Contain Specific String

/*filter rows where var1 contains "string1"*/
data specific_data;
    set original_data;
    where var1 contains 'string1';
run;

Method 2: Filter Row that Contain One of Several Strings

/*filter rows where var1 contains "string1", "string2", or "string3"*/
data specific_data;
    set original_data;
    where var1 in ('string1', 'string2', 'string3');
run;

The following examples show how to use each method with the following dataset in SAS:

/*create dataset*/
data nba_data;
    input team $ points;
    datalines;
Mavs 95
Spurs 99
Warriors 104
Rockets 98
Heat 95
Nets 90
Magic 99
Cavs 106
;
run;

/*view dataset*/
proc print data=nba_data;

Method 1: Filter Rows that Contain Specific String

The following code shows how to filter the dataset for rows that contain the string “avs” in the team column:

/*filter rows where team contains the string 'avs'*/
data specific_data;
    set nba_data;
    where team contains 'avs';
run;

/*view resulting rows*/
proc print data=specific_data;

The only two rows shown are the ones where the team column contains ‘avs’ in the name.

Method 2: Filter Rows that Contain One of Several Strings

The following code shows how to filter the dataset for rows that contain the strings “Mavs”, “Nets”, or “Rockets” in the team column:

/*filter rows where team contains the string 'Mavs', 'Nets', or 'Rockets'*/
data specific_data;
    set nba_data;
    where team in ('Mavs', 'Nets', 'Rockets');
run;

/*view resulting rows*/
proc print data=specific_data;

The following tutorials explain how to perform other common tasks in SAS:

x