Table of Contents
In the realm of SAS programming, the DO UNTIL statement serves as an essential mechanism for expertly controlling the flow of execution within a DATA step or a macro environment. This fundamental structure enables the repeated execution of a specific block of code until a designated logical condition is met and subsequently evaluates to true. Understanding the functional differences between this construct and others is critical for efficient programming; unlike its pre-test counterpart, the DO WHILE loop, the DO UNTIL loop is uniquely distinguished by its guarantee of executing the enclosed statements at least once, because the termination condition is assessed only at the conclusion of each iteration.
Mastering the effective utilization of DO UNTIL loops is foundational for conducting dynamic and iterative processing tasks in SAS. These tasks frequently involve complex scenarios such as modeling data simulations until convergence, executing sophisticated calculations that must run until a predetermined numerical threshold is reached, or generating sequential data structures where the final count of observations is not fixed or known beforehand. The inherent ability of the loop to perform an initial set of actions before checking any conditional constraints makes it optimally suited for programming requirements where a setup routine or initial computation is always necessary before any decision to continue or halt execution can be made.
This expert guide provides a highly detailed exploration of the practical application of the DO UNTIL statement within the SAS environment. We will meticulously examine two crucial, real-world examples that clearly demonstrate how to structure and manage these loops for the dynamic generation of values for variables that ultimately populate a new dataset. The examples are structured to transition from a straightforward, dependency-based implementation to a more advanced usage that strategically incorporates the indexed capabilities of the TO statement for combined iteration and conditional control.
The Mechanics of Post-Test Execution in DO UNTIL
The DO UNTIL loop in SAS operates as a highly specialized control statement designed for repetitive execution of a code block. Its fundamental operational characteristic dictates that the loop continues execution indefinitely until the specified termination condition finally evaluates to true. This structure is known as a post-test loop, meaning the control logic is applied only after the statements within the loop body have been fully executed. This design makes it the optimal choice for programming situations where the precise number of iterations required is not easily quantifiable at the start, but instead depends dynamically on how the variables evolve or change during the runtime of the loop itself.
The most defining feature of the DO UNTIL loop is this post-test execution model. The condition that determines whether to halt execution is rigorously checked only at the very end of each iteration, specifically after the statements nested within the loop have successfully completed their run. This critical execution sequence guarantees that the logic inside the loop body is executed at least one time, irrespective of the initial truth value of the termination condition. This guaranteed initial execution is often vital for many analytical and data generation tasks where an initial calculation, setup operation, or required action must always precede any decision to halt the repetitive process.
When constructing loops using the DO UNTIL statement, it is absolutely essential to incorporate specific logic that systematically modifies the variables influencing the termination condition. Neglecting to ensure that the condition eventually becomes true will inevitably result in an infinite loop. An infinite loop represents a severe programming issue where the program executes indefinitely without reaching an exit point, rapidly consuming system resources and potentially crashing the SAS session. Therefore, careful and systematic planning of how the involved variables are updated within the loop body is paramount for achieving reliable, predictable, and efficient code execution.
Core Syntax and Management of Termination Conditions
The fundamental syntax required to implement a DO UNTIL loop in SAS is remarkably straightforward: DO UNTIL (condition); ... END;. The element designated as condition must be a valid logical expression that SAS evaluates immediately after the entire block of code inside the loop has finished executing for that current iteration. The loop will persistently continue its iterative process as long as this logical expression remains false. However, the moment the expression yields a true result, the loop immediately terminates, and program control proceeds directly to the statements following the concluding END; keyword.
It is considered standard and necessary practice that the statements encapsulated within the DO UNTIL block include explicit modifications to the variables that are utilized in the termination condition. This proactive modification is absolutely essential to ensure that the loop makes tangible, measurable progress toward its designated exit point. If the variables governing the termination condition are not systematically updated, the condition may never be satisfied, inevitably leading to the notorious infinite loop scenario. For instance, if the termination condition is defined as (X > 100), then the logic inside the loop body must contain an instruction that reliably increases the value of X with each pass until it successfully surpasses 100.
A key statement frequently employed within DO UNTIL loops, especially when the objective is dynamic data generation, is the OUTPUT statement. This instruction is used to explicitly write a new observation (or row) to the target dataset during each iteration of the loop. By placing OUTPUT inside the loop body, the dynamically calculated current values of all relevant variables are recorded. This critical data recording process occurs just before the loop checks the termination condition, allowing for precise, iterative control over the evolving data structure and ensuring that the final, conditional value is captured if required.
Example 1: Basic Conditional Dataset Creation
This initial example provides a clear illustration of the fundamental use of the DO UNTIL statement within a simple, self-contained SAS DATA step. Our objective here is to construct a new dataset, named my_data, which will systematically grow to hold the calculated values for two primary variables: var1 and var2. The loop is precisely configured to continually generate and update the values for these variables until the value assigned to var1 finally exceeds a predetermined threshold of 100.
/*create dataset using DO UNTIL statement*/
data my_data;
var1 = 1;
var2 = 1;
do until(var1 > 100);
var1 = var1 + var2;
var2 = var1 * var2;
var1 + 1;
output;
end;
run;
/*view dataset*/
proc print data=my_data;

In the provided code block, both control variables, var1 and var2, are critically initialized with a starting value of 1. Inside the DO UNTIL loop, the variable var1 undergoes an update by incorporating the current value of var2, and subsequently, var2 is recalculated by multiplying the newly updated var1 by the previous value of var2. The crucial OUTPUT statement then records these dynamically calculated current values, writing them as a new, complete row into the my_data dataset. This process of dynamic data generation repeats continuously, with the termination condition (var1 > 100) being checked immediately after the data output is fully completed for each iteration, confirming the post-test behavior.
The primary function of the DO UNTIL statement here is to ensure that the sequential updates to var1 and var2 are persistently calculated and appended to the dataset, creating a chain of dependent values. This iterative process continues precisely until the moment the specified logical condition—where the value of var1 becomes numerically greater than 100—is successfully satisfied. Owing to the inherent post-test nature of this loop structure, the statements within the block are guaranteed to execute at least once, confirming that at least one observation is always added to the dataset, regardless of the initial starting states of the variables. It provides reliability in data generation where initialization steps must occur.
Example 2: Combining Conditional and Indexed Iteration
This second, more advanced example demonstrates the powerful technique of integrating the DO UNTIL statement with the indexed iteration capabilities provided by a TO statement. This strategic combination enables the creation of a hybrid loop structure that is initially designed to run for a specific, predetermined number of times, but includes an overriding conditional trigger that can halt its execution prematurely based on runtime calculations. We will again create a dataset, generating values for var1 and var2, but the loop will cease operations immediately if the calculated value of var1 exceeds the smaller threshold of 10.
/*create dataset using DO UNTIL statement with TO statement*/
data my_data;
var1 = 0;
do var2 = 1 to 5 until(var1 > 10);
var1 = var2**2;
output;
end;
run;
/*view dataset*/
proc print data=my_data;

In this sophisticated setup, the DO loop is initially structured to iterate the control variable var2 sequentially from 1 TO 5. However, this count-based iteration is fundamentally modified by the concurrent inclusion of the UNTIL condition, (var1 > 10). This means the loop will execute for the specified range of var2 values, but it possesses the critical capability to stop immediately if the calculated value of var1 surpasses 10. This conditional termination occurs regardless of whether var2 has successfully reached its upper bound of 5, thus providing dual control over the iteration process.
The inclusion of the TO statement defines the default maximum number of structured iterations for the index variable var2, acting as a failsafe count. Conversely, the concurrent DO UNTIL condition serves as a crucial, overriding termination trigger based on the dynamic data values. The process of adding new observations to the dataset will cease precisely at the moment var1 exceeds 10. As demonstrated in the output of the example code, var1 reaches 16 when var2 is 4 (since 4 squared is 16), causing the loop to terminate early, before var2 ever has a chance to increment to 5. This ensures computational efficiency by stopping unnecessary processing once the data constraint is breached.
Best Practices for Robust DO UNTIL Implementation
To ensure that code utilizing the DO UNTIL loop in SAS is both robust and predictable, programmers must rigorously adhere to several key best practices centered around loop control. The most paramount concern is guaranteeing the eventual and unavoidable fulfillment of the termination condition. A failure to correctly and consistently update the variables referenced in the conditional logic within the loop body can easily lead to an unintended and catastrophic infinite loop, which will either halt program execution or rapidly exhaust system resources. Careful variable management is the cornerstone of successful iterative programming.
Proper and thorough initialization of all variables involved in the loop logic is crucial before the DO UNTIL loop begins execution. Clear initialization establishes a necessary and well-defined starting point for all subsequent calculations and ensures that the termination condition can be reliably assessed during its initial post-test evaluation. Furthermore, the internal logic of the loop must systematically progress the variables toward satisfying the condition. For example, if the required condition is that a counter must reach the value of 10, the loop must contain an instruction that increments the counter during every iteration, ensuring forward movement.
It is also essential for advanced programmers to understand the fundamental functional difference between DO UNTIL (the post-test structure) and DO WHILE (the pre-test structure). A DO WHILE loop checks its condition at the very start of an iteration, meaning the body of the loop may not execute even once if the condition is initially false. In direct and crucial contrast, DO UNTIL guarantees at least one execution because the conditional check is strategically postponed until the end. The choice between these two powerful control structures should depend entirely on whether your programming logic demands an initial action before any conditional evaluation takes place.
Conclusion and Further Learning
The DO UNTIL statement is recognized as an indispensable and highly flexible tool in advanced SAS programming. It grants developers precise control over loop execution, dynamically adapting its behavior based on evolving data conditions rather than fixed iteration counts. Its unique post-test evaluation feature ensures that the loop body is executed at least once, making it exceptionally well-suited for a broad range of data processing and generation tasks where an initial calculation or setup action is an absolute requirement for the logical flow.
By fully grasping its core syntax and deeply understanding its execution behavior—particularly when strategically combined with other loop control options such as the indexed TO statement—you can significantly enhance the efficiency, dynamism, and reliability of your SAS programs. Always maintain vigilance in defining your termination conditions and meticulously confirm that the variables within your loop are updated correctly to proactively prevent runaway infinite loops and ensure program stability.
For programmers aiming to deepen their overall SAS programming expertise, it is highly recommended to explore other types of loops and various control structures available within the DATA step. The following resources offer additional, essential insights into common SAS tasks and programming techniques:
Cite this article
Mohammed looti (2025). Learning the DO UNTIL Statement: A Comprehensive Guide to Iteration in SAS Programming. PSYCHOLOGICAL STATISTICS. Retrieved from https://statistics.arabpsychology.com/use-a-do-until-statement-in-sas/
Mohammed looti. "Learning the DO UNTIL Statement: A Comprehensive Guide to Iteration in SAS Programming." PSYCHOLOGICAL STATISTICS, 14 Nov. 2025, https://statistics.arabpsychology.com/use-a-do-until-statement-in-sas/.
Mohammed looti. "Learning the DO UNTIL Statement: A Comprehensive Guide to Iteration in SAS Programming." PSYCHOLOGICAL STATISTICS, 2025. https://statistics.arabpsychology.com/use-a-do-until-statement-in-sas/.
Mohammed looti (2025) 'Learning the DO UNTIL Statement: A Comprehensive Guide to Iteration in SAS Programming', PSYCHOLOGICAL STATISTICS. Available at: https://statistics.arabpsychology.com/use-a-do-until-statement-in-sas/.
[1] Mohammed looti, "Learning the DO UNTIL Statement: A Comprehensive Guide to Iteration in SAS Programming," PSYCHOLOGICAL STATISTICS, vol. X, no. Y, ص Z-Z, November, 2025.
Mohammed looti. Learning the DO UNTIL Statement: A Comprehensive Guide to Iteration in SAS Programming. PSYCHOLOGICAL STATISTICS. 2025;vol(issue):pages.