SQL WHILE is an imperative control-flow construct that lets you create iterative loops in procedural extensions of SQL. On each iteration the Boolean condition is evaluated; if it returns TRUE the loop body runs, then control returns to the test. When the condition becomes FALSE the loop exits and execution continues with the statement that follows the WHILE block. WHILE is not part of the ANSI-SQL standard but is available in several dialects such as T-SQL (SQL Server and Sybase) and within stored-program languages in MySQL, PostgreSQL, and Oracle. Companion keywords BREAK and CONTINUE (or LEAVE/ITERATE) allow early exit or skipping to the next iteration. Because the same query can be executed set-based, overusing WHILE can hurt performance. Use it only when row-by-row logic, complex procedural branching, or retry logic is unavoidable.
condition
(Boolean expression) - Evaluated before each iteration.statement_block
(statement or BEGIN...END block) - Code that runs while the condition is TRUE.Sybase SQL Server 4.x (early T-SQL)
It evaluates a condition and runs a statement block repeatedly while that condition stays TRUE.
Yes, but only inside stored procedures, functions, or triggers. The syntax uses WHILE ... DO ... END WHILE.
Always change the loop variable or include logic that eventually makes the condition FALSE.
Set-based UPDATE or INSERT statements, window functions, and cursors can often replace explicit loops.