WHERE and IF Statements in SAS

Master the difference between WHERE and IF Statements in SAS for efficient data filtering. Learn when to use WHERE statements for speed on existing variables and IF statements for new variables. Our guide includes syntax examples, performance tips, and helps you avoid common subsetting errors to clean your datasets faster.

Differentiate between WHERE and IF Statements in SAS

There is a fundamental difference between WHERE and IF Statements in SAS. The breakdown of differences between WHERE and IF statements in SAS is as follows:

Key Differences Where and If Statements in SAS

Where Statement in SAS

The WHERE statement in SAS acts as a filter at the source. It tells SAS only to read observations that meet a specific condition from the input dataset(s). This happens very early in the process, often before the Program Data Vector (PDV) is fully constructed.

When to use WHERE Statement in SAS: Almost always for simple filtering, especially when working with large datasets, as it significantly improves performance by reducing I/O.

Example 1: Basic Filtering in a DATA Step

data high_earners;
    set sashelp.class;
    where age > 13; /* Only reads observations where Age is >13 */
run;

In this case, observations where age <= 13 are never even loaded into the PDV for processing.

Example 2: Using a WHERE Dataset Option

This is very powerful in procedures or when merging.

proc print data=sashelp.class(where=(sex='F')); /* Prints only females */
run;

data combined;
    merge ds1(where=(valid=1)) /* Merge only valid records from ds1 */
          ds2;
    by id;
run;

IF Statement in SAS

The IF statement in SAS is a processing-time filter. The entire observation is read into the PDV, all variables are calculated, and then the IF condition is evaluated. If the condition is false, the OUTPUT statement is bypassed (for that observation), and SAS returns to the beginning of the Data Step to process the next observation.

When to use IF Statement in SAS: When your filtering condition involves variables created within the Data Step or requires complex logic that must be executed row-by-row.

Example 1: Filtering on a New Variable

data tall_people;
set sashelp.class;
height_inches = height * 2.54; /* Create a new variable */
if height_inches > 64; /* Subsetting IF statement;*/
/* Equivalent to: if height_inches <= 64 then delete; */
run;

This works perfectly because the new variable height_inches exists in the PDV by the time the IF statement is executed.

Example 2: Complex Row-by-Row Logic

data flagged_records;
set mydata;
if some_var = . then do; /* Check for missing value */
error_flag = 'M'; /* Set a flag */
error_count + 1; /* Increment a counter */
end;
if error_flag = 'M'; /* Output only the records with errors */
run;

This kind of multi-step logic is not possible with a WHERE statement.

What is the Special Case of Subsetting IF vs DELETE Statements?

A common use of an IF statement is the subsetting IF (if condition;). This outputs an observation only if the condition is true. Its logical opposite is if condition then delete; which deletes an observation if the condition is true.

data adults;
    set people;
    if age >= 18; * Output if true;
run;

/* Is logically equivalent to: */

data adults;
    set people;
    if age < 18 then delete; * Delete if true;
run;

WHERE or IF Statement: Which One to Use?

  • Use WHERE when:
    • You are filtering based on variables that exist in the input dataset.
    • You want the most efficient processing, especially for large data.
    • You are working in a PROC step (like PROC PRINT, PROC SORT).
    • You want to use special operators like CONTAINS or LIKE.
  • Use IF when:
    • You need to filter based on a variable created within the same Data Step.
    • Your filtering logic is complex and requires other SAS statements (like DO loops or ARRAY processing).
    • You are already reading every observation into the PDV for other necessary calculations, and the efficiency gain of WHERE is negligible.

The WHERE statement can be used …. IF statement cannot be used

  • WHERE statement can be used in procedures to subset data, while the IF statement cannot be used in procedures.
  • WHERE can be used as a data set option, while IF cannot be used as a data set option.
  • WHERE statement is more efficient than the IF statement. It tells SAS not to read all observations from the data set
  • WHERE statement can be used to search for all similar character values that sound alike, while the IF statement cannot be used.
  • WHERE statement can not be used when reading data using the INPUT statement, whereas the IF statement can be used.
  • Multiple IF statements can be used to execute multiple conditional statements
  • When it is required to use newly created variables, use an IF statement, as it doesn’t require variables to exist in the READIN data set.  

What is the one statement to set the criteria of data that can be coded in any step?

A WHERE statement can set the criteria for any data set in a data step or a proc step.

General Knowledge Quizzes

Understanding Advanced SAS Procedures

Master advanced statistical modeling in SAS with our detailed question-and-answer guide. This Understanding Advanced SAS Procedures post explains the core statements and functionality of essential SAS procedures like PROC NLIN for nonlinear regression, PROC NLMIXED for nonlinear mixed models, PROC GLIMMIX for linear and generalized linear mixed models, and PROC PROBIT for dose-response analysis. Learn how to use PARMS, MODEL, RANDOM, and CLASS statements correctly, avoid common syntax errors, and interpret your results with practical examples from the sashelp.cars and sashelp.iris datasets. Perfect for data analysts and statisticians looking to deepen their SAS programming skills.

Understanding Advanced SAS Procedures

Understanding Advanced SAS Procedures

Explain the following SAS Statements used in the Example below (Non-Linear Mixed Model)

proc nlmixed data = CARS;
parms b1 = 220 b2 = 500 b3 = 310 s2u = 100 s2e = 60;
model X ~ normal(num/den, s2e);
random u1 ~ normal(0, s2u) subject = NUMBER;
run;

This is an excellent example of a nonlinear mixed model in SAS. The MIXED MODEL statement defines the dependent variable and its conditional distribution given the random effects. In the above statement, a normal (Gaussian) conditional distribution is specified.

This code is fitting a nonlinear mixed-effects model to data about cars (from the CARS dataset). It is trying to estimate parameters ($b_1, b_2$, and $b_3$) for a specific nonlinear relationship between a predictor and the outcome $X$, while also accounting for random variations between different groups of cars (grouped by NUMBER).

The RANDOM statement defines the single random effect to be $u1$, and specifies that it follows a normal distribution with mean $0$ and variance $s2u$. The SUBJECT= statement in the RANDOM statement is used to define a variable that will indicate when the random effect obtains new realizations.

Explain the following SAS statements (Linear Mixed Model) in the example below

proc glimmix data = sashelp.iris;
class species;
model age = weight;
random age = weight;
run;

The CLASS statement instructs the technique to treat the variable species as type variables. The version announcement in the example shown above specifies the reaction variable as a pattern proportion by means of the use of the occasions/trials approach.

This PROC GLIMMIX code contains a critical error in its RANDOM statement, which makes the model, as written, invalid and nonsensical.

In code, it is trying to fit a linear mixed model to the sashelp.iris dataset (famous Fisher’s Iris data). The intent might have been to see how age (which does not exist in the standard iris dataset) is related to weight (which also does not exist), while accounting for the grouping structure of species. The syntax of the RANDOM statement is completely incorrect.

Explain the use of each SAS statement (PROC PROBIT) given below

PROC PROBIT dataset;
CLASS <dependent variables>;
Model < dependent variables > = <independent VARIABLES>;

This statement outlines the basic structure for using PROC PROBIT in SAS, but it contains a few common misunderstandings and a critical error in the CLASS statement. However, the line-by-line explanation of the code is:

The DATA= option specifies the dataset that will be studied.

The PLOTS= choice within the PROC PROBIT statement, collectively with the ODS graphics announcement, requests all plots (as all have been specified in brackets, we will pick out a selected plot also) for the anticipated opportunity values and peak ranges.

The model statement prepares a response between a structured variable and independent variables. The variables top and weight are the stimuli or explanatory variables.

Explain the following SAS example (PROC NLIN)

proc nlin data = sashelp.cars method = gauss;
parms hosepower = 135
cylinders = 6;
model mpg_highway = (horsepower/cylinders);
run;

This code is used to fit a nonlinear regression model (PROC NLIN) to car data. The METHOD = option directs PROC NLIN to use the GAUSS iterative method. The PARMS statement declares the parameters and specifies their initial values.

The code is trying to model a car’s highway fuel efficiency (mpg_highway) as a simple nonlinear function of its power (horsepower) and engine size (cylinders). Specifically, it is testing the hypothesis that highway MPG is directly proportional to the power-per-cylinder (horsepower / cylinders). The code contains a critical error in its model specification, which will cause it to fail.

R Frequently Asked Questions

MS Excel Pivot Table Quiz 18

Test your Excel Pivot Table skills with this 20-question MCQ quiz! This MS Excel Pivot Table Quiz is perfect for students, statisticians, data analysts, and data scientists preparing for exams or job interviews. Master Excel Pivot Table concepts like grouping, filtering, calculations, and custom lists to boost your data analysis efficiency. Excel Pivot Table Quiz, PivotTable MCQ, data analysis test, Excel interview questions, PivotTable exam prep. Let us start MS Excel Pivot Table Quiz now.

Online MS Excel Pivot Table Quiz with Answers

1. When in PivotTable Fields, if you tick a field that contains numeric data, it will automatically populate which quadrant?

 
 
 

2. If you want to filter by a field that you do not necessarily want to show in the PivotTable itself, you should move this field to which quadrant?

 
 
 
 

3. The main difference between Label Filters and Value Filters is that Label Filters are for filtering based on text.

 
 

4. If you choose Show Report Filter Pages after having selected multiple items in a filter, what would happen?

 
 
 
 

5. To clear a filter in a PivotTable, you could:

 
 
 
 

6. When in PivotTable Fields, if you tick a field that contains non-numeric data, it will automatically populate which quadrant?

 
 
 
 

7. One way to filter which columns and which rows appear in your PivotTable is to use the drop-down menu that appears next to Row Labels and Column Labels.

 
 

8. Converting your data into a Table before creating a PivotTable is a good idea because:

 
 
 

9. To change the calculation within your PivotTable, you get more options by right-clicking one of the values, compared to customizing the calculation in the Values quadrant.

 
 

10. When does Excel automatically give you sub-totals for your PivotTable?

 
 
 
 

11. Choosing the option Rank Smallest to Largest will result in the PivotTable being sorted and displayed from smallest to largest values.

 
 

12. A PivotTable currently occupies some of Columns A and B as per the screenshot. The formula that is displayed is typed into cell D4. What would happen to the result of the formula if the filters of the PivotTable were modified?
MS Excel Pivot Table Quiz 4

 
 
 

13. Before you create a PivotTable, you need to ensure that you have nice clean data with

 
 
 

14. If you have full dates and you create a PivotTable, Excel will group these dates, such as grouping by month. You can remove this by choosing Ungroup.

 
 

15. What would moving the Europe cell to elsewhere in the PivotTable do?
MS Excel Pivot Table Quiz

 
 
 

16. Which of the following buttons would we need to click to group the dates below?
MS Excel PivotTable

 
 
 
 
 

17. Which of the following buttons would we need to click to group a few rows from our PivotTable?
MS Excel PivotTable Quiz

 
 
 
 
 

18. You can choose to display a sub-total as a sum and as an average, and both these items will appear separately at the bottom of the respective section in your PivotTable.

 
 

19. Which of these are correct statements about custom lists in Excel?

 
 
 
 

20. Rather than seeing discrete values, if you want to see percentages instead, you should go to

 
 
 

Question 1 of 20

Online MS Excel Pivot Table Quiz with Answers

  • Before you create a PivotTable, you need to ensure that you have nice clean data with
  • Converting your data into a Table before creating a PivotTable is a good idea because:
  • When in PivotTable Fields, if you tick a field that contains numeric data, it will automatically populate which quadrant?
  • When in PivotTable Fields, if you tick a field that contains non-numeric data, it will automatically populate which quadrant?
  • To change the calculation within your PivotTable, you get more options by right-clicking one of the values, compared to customizing the calculation in the Values quadrant.
  • Rather than seeing discrete values, if you want to see percentages instead, you should go to
  • Choosing the option Rank Smallest to Largest will result in the PivotTable being sorted and displayed from smallest to largest values.
  • When does Excel automatically give you sub-totals for your PivotTable?
  • You can choose to display a sub-total as a sum and as an average, and both these items will appear separately at the bottom of the respective section in your PivotTable.
  • If you have full dates and you create a PivotTable, Excel will group these dates, such as grouping by month. You can remove this by choosing Ungroup.
  • Which of the following buttons would we need to click to group the dates below?
  • Which of the following buttons would we need to click to group a few rows from our PivotTable?
  • What would moving the Europe cell to elsewhere in the PivotTable do?
  • Which of these are correct statements about custom lists in Excel?
  • One way to filter which columns and which rows appear in your PivotTable is to use the drop-down menu that appears next to Row Labels and Column Labels.
  • To clear a filter in a PivotTable, you could:
  • The main difference between Label Filters and Value Filters is that Label Filters are for filtering based on text.
  • If you want to filter by a field that you do not necessarily want to show in the PivotTable itself, you should move this field to which quadrant?
  • If you choose Show Report Filter Pages after having selected multiple items in a filter, what would happen?
  • A PivotTable currently occupies some of Columns A and B as per the screenshot. The formula that is displayed is typed into cell D4. What would happen to the result of the formula if the filters of the PivotTable were modified?
Online MS Excel Pivot Table Quiz 4

Try Macroeconomics MCQs Test