What Is a Nested Loop?

internet computers

A nested loop is a logical structure used in computer programming where two repeating statements are placed in a "nested" form, i.e., one loop is situated within the body of the other. In a nested loop, the first iteration of the outer loop causes the inner loop to execute. The inner loop then repeats for as many times as is specified. When the inner loop completes, the outer loop is executed for its second iteration, triggering the inner loop again, and so on until the requirements for the outer loop are complete.

Looping, and by extension nested looping, is a powerful construct in programming as it allows rapid sorting or insertion of large amounts of data in an efficient way. Solving problems in the business world often involves repeating an action over and over with hundreds, thousands, or even millions of items of data. Nested loops are therefore frequently used constructs in all kinds of computer programs in all types of industry.

More than two loops can be nested, and nested loops can go as deep as required. To take an example from the real world which explains the idea of multiple nested loops, consider the car odometer. It is easy to imagine the leftmost digit of the odometer as the outermost nested loop, and each successive digit as another loop, each within the other, until one reaches the rightmost digit, which represents the innermost nested loop.

For those programmers working in Structured Query Language (SQL), the nested loop join construct is of particular relevance. This is a means by which one can quickly and efficiently search data in two linked tables. An outer loop is used to read the first table, one row of data at a time. Then the data required to search the second table is passed to the inner loop, which reads the second table. The nested loop join can thus process two linked tables in an efficient manner.

The method used to set up nested loops varies between programming languages. In SQL, for example, one may script nested loop structures and execute these loops either as a server nested loop that is called remotely or as a nested loop on a client machine that is executed locally. In order to use these powerful structures effectively, it is necessary to take into consideration both the language used by the program and the database or other backend that is being queried for the data.

Related wiseGEEK articles

Category

wiseGEEK features

Subscribe to wiseGEEK


FREE: Subscribe to wiseGEEK

 
    learn more

our strict privacy policy ensures that your email address will be safe



Written by C. Martin


copyright © 2003 - 2009
conjecture corporation