## Number of Observations in a SAS Dataset

Occasional Contributor
Posts: 13

# Number of Observations in a SAS Dataset

Hi Friend,

I have good SQL knowledge but new SAS learner, I need to count total number of observation from one data set

I am following  below steps

data students;
input gender score;
cards;
1 48
1 45
2 50
2 42
1 41
2 51
1 52
1 43
2 52
;
run;

now I need total count from above table.

proc sql;
select count(*) from students1;
quit;

above queyr will give output 9 but when I am converting ths into SAS code

data students1;
set students;
count + 1;
by gender;
if first.gender then count = 1;
run;

proc print data = students1;
run;

above code I find out from the google and also this is not giving output 9. I am on a SAS learning stage . Please help

Super User
Posts: 10,280

## Re: Number of Observations in a SAS Dataset

First of all, this happens:

```31         data students1;
32         set students;
33         count + 1;
34         by gender;
35         if first.gender then count = 1;
36         run;

ERROR: BY variables are not properly sorted on data set WORK.STUDENTS.```

So you have to do

``````proc sort data=students;
by gender;
run;``````

before you try that data step.

Now you get that output:

```                                                  Obs    gender    score    count

1        1        48       1
2        1        45       2
3        1        41       3
4        1        52       4
5        1        43       5
6        2        50       1
7        2        42       2
8        2        51       3
9        2        52       4
```

You can see that the final counts for both values of gender add up to 9.

To get a simple total count, do this:

``````data students1;
set students;
count + 1;
run;``````

Now, you can get the total number of observations in a dataset much easier (and quicker, once the datasets grow) by querying its metadata&colon;

``````proc sql;
select nobs from dictionary.tables where libname = 'WORK' and memname = 'STUDENTS';
quit;``````
---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
Super User
Posts: 23,773

## Re: Number of Observations in a SAS Dataset

Although you can count the number of obs using a data step you probably shouldn't. There are many ther ways to do so, one being querying the metadata tables and another is using a summary proc such as proc means or proc freq.

proc means data=students;

class gender;

run;

proc freq data=students;

tables gender;

run;

Discussion stats
• 2 replies
• 1588 views
• 0 likes
• 3 in conversation