Search code examples
sas

How can I output a certain number of observations satisfying a where statement in SAS


For example I want to output only the first 5 observations in the table CARS which satisfies the WHERE statement that Horsepower is greater than 265.

DATA test(obs=5);
SET SASHELP.CARS;
WHERE Horsepower > 265;
RUN;

The above doesn't work. This seems very simple but I'm not sure how to achieve what I want here.


Solution

  • Use if(_N_ > 5) then stop.

    data want;
        set sashelp.cars;
        where horsepower > 265;
        if(_N_ > 5) then stop;
    run;
    

    Or, use SQL outobs

    proc sql outobs=5;
        create table want as
            select *
            from sashelp.cars
            where horsepower > 265
        ;
    quit;