How do I change the length of character variables in SAS?

In SAS, the length of character variables can be changed using the LENGTH statement. This statement defines the length of a character variable as a number of bytes. The number of bytes is specified in the LENGTH statement and can be any integer from 1 to 32,000. The default length is 200 bytes. It is important to make sure that the length of the variable is sufficient to store the maximum length of the string that is expected. If the length of the variable is too small, SAS will truncate the string. If the length of the variable is too large, SAS will waste memory. Therefore, setting the correct length is important for efficient programming.


The easiest way to change the length of character variables in SAS is to use the ALTER TABLE and MODIFY statements within PROC SQL.

You can use the following basic syntax to do so:

proc sql;
    alter table my_data
    modify team char(4);
quit;

This particular example modifies the length of the character variable called team in the dataset called my_data to have a length of 4.

The following example shows how to use this syntax in practice.

Example: Change Length of Character Variable in SAS

Suppose we have the following dataset in SAS that contains information about various basketball teams:

/*create dataset*/
data my_data;
    input team $ points;
    datalines;
Cavs 12
Cavs 24
Heat 15
Cavs 26
Heat 14
Mavs 36
Mavs 19
Nets 20
Nets 31
;
run;

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

We can use to view the length of each variable in the dataset:

/*view length of each variable in dataset*/
proc contents data=my_data;

The last table in the output shows the length of each variable:

From this table we can see:

  • The points variable is a numeric variable with a length of 8.
  • The team variable is a character variable with a length of 8.

Suppose we would like to change the team variable to have a length of 4.

We can use the following syntax to do so:

/*change length of team variable to 4*/
proc sql;
    alter table my_data
    modify team char(4);
quit;

We can use them use PROC CONTENTS once again to view the length of each variable in the dataset:

/*view updated length of each variable in dataset*/
proc contents data=my_data;

The last table in the output shows the length of each variable:

We can see that the team variable now has a length of 4.

It’s worth noting that none of the values in the team column were truncated because the longest team name had a length of 4.

However, if you changed the length of the team variable to 3, for example, then the last character of some team names would have been truncated.

Using this method, no warning message will appear if truncation occurs so make sure you know the maximum length of strings in your character column before you use this method.

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

x