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

Hi community,

Are the results of a PROC SQL's "Select distinct" always given in sorted order?

Or are there data arrangements (maybe with indexes?) that would/could affect the order of the results?

 

I can't find any documentation where the operations behind "Distinct" are explicitely described

I've performed some tests on indexes datasets but it seems that the results are always sorted.

(I've never questionned that, but I am doing now)

I'm not using any groups and the order variable I need is always the "distinct" variable.

 

data class(index=(sex));
set sashelp.class;
run;
proc sort data=class force;by sex name;run;

proc sql;
select distinct age
from sashelp.class
;
*same results as;
select distinct age
from class
;
quit;

I'd be grateful if you could share some piece of information on this.

Thanks

________________________

- Cheers -

1 ACCEPTED SOLUTION

Accepted Solutions
Quentin
Super User

Probably, but it's also not a good idea to assume that it always will.

 

Generally, SQL is a set language (as in logical sets), and order doesn't matter for sets.  So the same query will sometimes reorder data and sometimes will not, depending on how the SQL optimizer decides to execute the query.

 

If you care about the order of the output data, you should always add an ORDER BY clause.

View solution in original post

1 REPLY 1
Quentin
Super User

Probably, but it's also not a good idea to assume that it always will.

 

Generally, SQL is a set language (as in logical sets), and order doesn't matter for sets.  So the same query will sometimes reorder data and sometimes will not, depending on how the SQL optimizer decides to execute the query.

 

If you care about the order of the output data, you should always add an ORDER BY clause.

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
  • 1 reply
  • 1526 views
  • 2 likes
  • 2 in conversation