How to Perform a Left Join in SAS (With Example)


You can use the following basic syntax to perform a left join with two datasets in SAS:

proc sql;
    create table final_table as
    select * from data1 as x left join data2 as y
    on x.ID = y.ID;
quit;

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

Related: How to Perform an Inner Join in SAS

Example: Left Join in SAS

Suppose we have the following two datasets in SAS:

/*create datasets*/
data data1;
    input team $ points;
    datalines;
Mavs 99
Spurs 93
Rockets 88
Thunder 91
Warriors 104
Cavs 93
Grizzlies 90
Hawks 91
;
run;

data data2;
    input team $ rebounds;
    datalines;
Mavs 21
Spurs 18
Rockets 22
Warriors 27
Cavs 15
Hawks 29
;
run;

/*view datasets*/
proc print data=data1;
proc print data=data2;

Notice that the two datasets share one variable in common: team.

We will use the following syntax to perform a left join and create a new dataset that contains every row from data1 and only the rows from data2 that match a team name in data1:

/*perform left join*/
proc sql;
	create table final_table as
	select * from data1 as x left join data2 as y
	on x.team = y.team;
quit;

/*view results of left join*/
proc print data=final_table;

The resulting dataset contains every original team from data1, but the only teams that have values for the rebounds column are the ones that also appeared in data2.

Additional Resources

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

How to Normalize Data in SAS
How to Replace Characters in a String in SAS
How to Replace Missing Values with Zero in SAS
How to Remove Duplicates in SAS

Leave a Reply

Your email address will not be published.