Written and maintained by CASRAI Editorial Board
Published
On this page
The SAS MERGE statement joins observations from two or more existing SAS data sets into a single observation inside a DATA step. Without a BY statement it combines rows by position (a one-to-one merge); with a BY statement it matches rows on shared key variables (a match-merge), and every input data set must then be sorted by those variables or have an appropriate index. In research data work, merge is how you attach, for example, a baseline file to follow-up measurements using a participant identifier.
What the SAS MERGE statement is used for in research
Most study data arrive in separate tables: demographics, laboratory results, outcome assessments, site records. The MERGE statement in the DATA step brings those tables together so that one row holds everything known about one unit. The SAS statement reference gives the syntax as MERGE followed by at least two data set names, each optionally carrying data set options, plus an optional END= variable that is 0 until the last observation is read and 1 on it (it is not written to the output).
Two behaviours matter before you write any code. First, unlike several SET statements, which stop when one input runs out, MERGE keeps processing until all observations of all data sets have been read. Second, when the BY groups have different sizes, the merge pads the shorter side with missing values rather than dropping rows. Both points come from the SAS documentation and explain why a merge can silently change your row count.
One-to-one merge versus match-merge
The documentation draws the line at the BY statement. To perform a one-to-one merge, you use the MERGE statement without a BY statement; observations are combined in the order they appear in each data set, and the new data set has as many observations as the largest input. To perform a match-merge, you place a BY statement immediately after MERGE. The documentation warns that a one-to-one merge can sometimes produce undesirable results, so in research data (where rows should align by an identifier, not by position) the match-merge is the form you normally want.
Many-to-many merges in SAS
If a BY value appears more than once in two or more of the inputs, SAS does not build every combination of rows. The documentation states that MERGE does not produce a Cartesian product on a many-to-many match-merge. Instead it performs a one-to-one merge while the BY group still has observations in at least one data set, then continues as a one-to-many merge until the BY group is exhausted. A SQL join on the same data would return a Cartesian product, so the two approaches can give different row counts; see the SAS PROC SQL guide for the SQL route.
How to install or access SAS
MERGE is part of the SAS language, so you need SAS itself. Your institution may provide it; otherwise SAS describes SAS OnDemand for Academics as a free, cloud-based learning environment that gives access to SAS software without installing or managing it locally. Its SAS Studio edition runs in a web browser and lets you access data and write SAS programs. According to the SAS page, students in a class register with a code from their instructor, while independent learners can access Studio without a class code through the site named on the page (welcome.oda.sas.com). SAS Enterprise Guide, the point-and-click interface, requires a registered course. Follow the registration steps on the official page, because the options differ by user type.
How to merge datasets in SAS step by step
This sequence follows the documentation’s requirement that match-merge inputs be sorted, and the pattern shown in the UCLA OARC match-merge module. Replace the data set and variable names with your own.
- Identify the key. Choose one or more variables that exist, with the same name, in every data set you are merging. The documentation requires the BY variables to be common to all inputs, and a MERGE statement takes only one BY statement.
- Sort each input by the key. Use PROC SORT with OUT= so the original is left intact:
proc sort data=dads out=dads2; by famid; run;. The PROC SORT documentation describes OUT= as creating a new data set for the sorted observations. Repeat for every data set. If a data set is already sorted or indexed on the key, the documentation allows that too. - Write the DATA step.
data dadfam; merge dads2 faminc2; by famid; run;. The MERGE statement lists the inputs; the BY statement immediately after it makes this a match-merge. - Add IN= flags if you need to know where each row came from.
merge dads(IN=fromdadx) faminc(IN=fromfamx); by famid;. The IN= data set option creates a Boolean variable that is 1 if that data set contributed to the current observation and 0 otherwise. - Subset on the flags if you want a specific join. See the table below.
- Check the result. Compare the observation count with what the documentation predicts (see the output section) and print the rows where a flag is 0.
Merging with a data set list
The MERGE statement accepts a list: a numbered range such as d008-d011 and a prefix list ending in a colon are both allowed, and the documentation says physical paths cannot be used in the list. The statement reference’s own example illustrates it with four one-variable-per-file data sets:
data d008; job=3; emp=19; run;data d009; job=3; sal=50; run;data d010; job=4; emp=97; run;data d011; job=4; sal=15; run;data comb; merge d008-d011; by job;run;
Applying the documented match-merge logic, the result is two observations: job 3 with emp 19 and sal 50, and job 4 with emp 97 and sal 15. This output is derived from the merge rules, not copied from the page.
Choosing the join with IN= flags
MERGE keeps every observation from every input by default, which corresponds to a full join. Because the IN= variable is 1 only when that data set contributed to the current observation, a subsetting IF on the flags restricts the output. The mapping below is an editorial application of that documented definition; name your flags as you like (a and b here).
| Goal | Statement after BY | Rows kept |
|---|---|---|
| Full join (default) | none | Every key from either data set |
| Inner join | if a and b; |
Keys present in both data sets |
| Left join | if a; |
All keys from the first data set, with second-data-set variables missing where unmatched |
| Anti-join (first only) | if a and not b; |
Keys in the first data set with no match in the second |
The IN= variables are not written to the output data set unless you assign them to a new variable, as the UCLA example does with fromdad = fromdadx;. Also note that the IN= option is valid only in a DATA step with SET, MERGE, MODIFY or UPDATE.
How to read the output
The documentation gives two row-count rules you can test against your log. In a one-to-one merge the output has as many observations as the largest input. In a match-merge, for each BY value the output has as many observations as the largest count of that value in any one input, and the total is the sum across BY values. If your count is higher than you expected, a key probably repeats in an input; if it is lower than the sum of the inputs, that is normal, since matching rows collapse into one.
Unmatched keys are retained with missing values for the variables from the data set that did not contribute. The UCLA OARC module shows this: a key present only in the first file keeps that file’s values and shows missing values for the second file’s variables, and the reverse for a key present only in the second file. Its advice is to investigate the cause of mismatched records, and to use IN= flags copied into permanent variables so you can filter on them (for example with a WHERE statement in PROC PRINT).
A small worked example
This is an illustrative composite, not data from any study. Suppose baseline holds subjects 1, 2 and 3 with variable age, and followup holds subjects 2, 3 and 4 with variable score, both sorted by subject.
data both; merge baseline(in=a) followup(in=b); by subject; inbase = a; infu = b;run;
Under the documented rules the result has four rows: subject 1 (age present, score missing, inbase=1, infu=0), subjects 2 and 3 (both present, flags 1 and 1) and subject 4 (age missing, score present, inbase=0, infu=1). Adding if a and b; would leave only subjects 2 and 3.
Troubleshooting SAS MERGE
The result has rows that do not line up
Check whether you left out the BY statement. Without it the merge is by position, and the documentation says this can sometimes produce undesirable results. Since a one-to-one merge is a valid form of the statement, check the code for the BY line first.
The BY variable is not accepted or sorting fails
The documentation requires the data sets in a match-merge to be sorted in order of the BY variables (or indexed appropriately), and the BY variables must be common to all inputs. Sort each input with PROC SORT by the same variables, in the same order, as the BY statement in the DATA step. Keep the sort in a separate step from the merge so a failure points to one cause.
Row counts look wrong with repeated keys
Repeated keys in more than one input behave as described under many-to-many: no Cartesian product. If you need every combination, use a SQL join instead; if you only need to find the duplicates, compare the inputs first with PROC COMPARE.
A data set name will not resolve in the list
Data set lists accept name prefixes and numbered ranges, not physical file paths. Assign a library with a LIBNAME statement and refer to the data set as library.name.
The flag variable is missing from the output
That is the documented behaviour of IN=: the variable exists only while the DATA step runs. Assign it to a new variable to keep it.
Reshaping before merging
If one file is long (several rows per subject) and the other wide, decide on the unit of observation first. The PROC TRANSPOSE guide covers reshaping so that keys are unique before you merge.
Free alternatives to SAS
If you do not have a SAS licence, the same joins exist in open scientific tools. The table compares the documented behaviour of each; the main difference is the default. SAS MERGE keeps all keys, while pandas defaults to an inner join. Readers who work in Stata can also see merging datasets in Stata.
| Tool | Function | Documented join controls |
|---|---|---|
| R (base) | merge() |
Merges two data frames by common columns or row names; by selects the columns, all.x = TRUE adds a row for each row in x with no match in y, and all sets all.x and all.y together |
| Python (pandas) | pandas.merge() |
how accepts left, right, outer, inner, cross (default inner); on names the key columns |
| SAS OnDemand for Academics | The SAS MERGE statement itself | Browser-based SAS Studio, described by SAS as a free, cloud-based learning environment |
Sources
- SAS Institute: MERGE Statement, SAS Statements Reference, checked 2026-11-17
- SAS Institute: IN= Data Set Option, checked 2026-11-17
- SAS Institute: SORT Procedure, checked 2026-11-17
- SAS Institute: SAS OnDemand for Academics, checked 2026-11-17
- UCLA OARC: Match merging data files in SAS, checked 2026-11-17
- pandas documentation: pandas.merge, checked 2026-11-17
- R Documentation: merge (base), checked 2026-11-17
Data: SAS MERGE join behaviour and equivalent open-source controls
Compares how the SAS DATA step MERGE statement, the R base merge() function and pandas.merge() control which keys are kept, compiled from each tool's official documentation read on 2026-11-17. Cells paraphrase the documented behaviour.
| Tool | Function | Keeps unmatched keys | Control over join type |
|---|---|---|---|
| SAS | MERGE statement with BY | Yes: all observations of all data sets are processed | IN= flags with a subsetting IF |
| R (base) | merge() | Extra rows for unmatched keys are added when all.x or all.y is TRUE | all, all.x, all.y |
| Python (pandas) | pandas.merge() | Depends on how; default is inner | how: left, right, outer, inner, cross |
Sources
- SAS MERGE Statement (accessed 2026-11-17)
- R merge documentation (accessed 2026-11-17)
- pandas.merge (accessed 2026-11-17)
- SAS IN= data set option (accessed 2026-11-17)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







