BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
aalluru
Obsidian | Level 7

I'm joining table a with table b using a left join and I want the resultant table to be in the same order that table a was in. However the order seems to be changing to the ascending order of the variable that I used to join on. How can I prevent that from happening?

1 ACCEPTED SOLUTION

Accepted Solutions
FreelanceReinh
Jade | Level 19

Hi @aalluru,

 

In this case create your own (temporary) sort key and use that in the ORDER BY clause.

 

Example:

/* Create sample data for demonstration */

data have_a;
set sashelp.classfit;
keep name predict;
run;

data have_b;
set sashelp.class;
keep name age;
run;

/* Create view with a sort key (sequential number) */

data _have_a / view=_have_a;
set have_a;
_seqno=_n_;
run;

/* Perform left join maintaining sort order of HAVE_A and delete the view */

proc sql;
create table want(drop=_seqno) as
select a.*, age
from _have_a a left join have_b b
on a.name=b.name
order by _seqno;

drop view _have_a;
quit;

 

View solution in original post

4 REPLIES 4
maguiremq
SAS Super FREQ

Do you know what the table on the left was ordered by originally? You can use an `ORDER BY` clause after your join if it's that simple.

 

You'd probably need to specify the variable that it was sorted on along with its alias (e.g., ORDER BY a.unique_id).

aalluru
Obsidian | Level 7

The table on the left was in a random order

FreelanceReinh
Jade | Level 19

Hi @aalluru,

 

In this case create your own (temporary) sort key and use that in the ORDER BY clause.

 

Example:

/* Create sample data for demonstration */

data have_a;
set sashelp.classfit;
keep name predict;
run;

data have_b;
set sashelp.class;
keep name age;
run;

/* Create view with a sort key (sequential number) */

data _have_a / view=_have_a;
set have_a;
_seqno=_n_;
run;

/* Perform left join maintaining sort order of HAVE_A and delete the view */

proc sql;
create table want(drop=_seqno) as
select a.*, age
from _have_a a left join have_b b
on a.name=b.name
order by _seqno;

drop view _have_a;
quit;

 

aalluru
Obsidian | Level 7
Yes! This worked! Thank you!!

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 5016 views
  • 1 like
  • 3 in conversation