A plain SQL query has no FOR loop; you get loops from your database's procedural language instead. In PostgreSQL that is FOR i IN 1..10 LOOP inside PL/pgSQL, in SQL Server it is WHILE, and for many jobs a recursive CTE or generate_series replaces the loop altogether.
The examples below are grouped by database, because the syntax is not portable. SQL Server's WHILE will not run in PostgreSQL, and PL/pgSQL's FOR will not run in SQL Server. If you are new to the language itself, start with SQL for beginners.
SQL for loop in PostgreSQL (PL/pgSQL)
PL/pgSQL is PostgreSQL's procedural language. It has an integer FOR loop with this syntax, taken from the PostgreSQL documentation:
FOR name IN [ REVERSE ] expression .. expression [ BY expression ] LOOP
statements
END LOOP;
The loop variable is an integer that exists only inside the loop. REVERSE counts down, and BY sets the step. The documentation's own example is FOR i IN REVERSE 10..1 BY 2 LOOP, where i takes the values 10, 8, 6, 4 and 2. If the lower bound is greater than the upper bound, the body does not run and no error is raised.
You cannot write that loop at the top level of a query. It has to live inside a function, a procedure or a DO block. A DO block runs anonymous code once:
DO $$
BEGIN
FOR i IN 1..5 LOOP
RAISE NOTICE 'i = %', i;
END LOOP;
END;
$$;
Example output (psql prints one notice per pass):
NOTICE: i = 1
NOTICE: i = 2
NOTICE: i = 3
NOTICE: i = 4
NOTICE: i = 5
Loop over the rows of a query
The second FOR form iterates over the result of a query. The documentation describes it this way: the target is assigned each row of the query in turn, and the loop body runs once per row.
DO $$
DECLARE
o record;
BEGIN
FOR o IN SELECT order_id, amount FROM orders WHERE amount > 100 LOOP
RAISE NOTICE 'order % is %', o.order_id, o.amount;
END LOOP;
END;
$$;
The orders table here is a stand-in for your own. The query after IN can be any command that returns rows. SELECT is the usual choice, but INSERT, UPDATE, DELETE or MERGE with a RETURNING clause also work.
SQL while loop in SQL Server (T-SQL)
Transact-SQL has no FOR statement. Its only loop is WHILE, which repeats a statement or a BEGIN ... END block as long as a Boolean condition is true. Microsoft documents BREAK to leave the innermost loop and CONTINUE to restart it. To count from 1 to 5 you manage the counter yourself:
DECLARE @i INT = 1;
WHILE @i <= 5
BEGIN
PRINT 'i = ' + CAST(@i AS VARCHAR(10));
SET @i = @i + 1;
END;
Example output, in the Messages tab:
i = 1
i = 2
i = 3
i = 4
i = 5
Forget the SET @i = @i + 1 line and the condition never becomes false, so the loop never ends. That is the most common mistake with WHILE.
Looping through rows with a cursor
To visit each row of a query in T-SQL, Microsoft's WHILE page shows a cursor driven by @@FETCH_STATUS. The loop continues while the status is 0, meaning the last fetch succeeded:
DECLARE @LoginID NVARCHAR(256);
DECLARE row_cursor CURSOR FOR
SELECT LoginID FROM HumanResources.Employee;
OPEN row_cursor;
FETCH NEXT FROM row_cursor INTO @LoginID;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @LoginID;
FETCH NEXT FROM row_cursor INTO @LoginID;
END;
CLOSE row_cursor;
DEALLOCATE row_cursor;
Note the second FETCH NEXT inside the loop. It moves to the next row, and without it the loop would print the first row forever. The table name comes from Microsoft's AdventureWorks sample database; replace it with your own.
Generate a sequence without a loop: generate_series
Often the reason people search for a SQL for loop is to produce a run of numbers or dates. In PostgreSQL, generate_series does that in one query. Its integer form is generate_series(start, stop [, step]), and the step defaults to 1.
SELECT * FROM generate_series(5, 1, -2);
This is the documentation's own example. It returns 5, 3 and 1. With a positive step it returns no rows if start is greater than stop, with a negative step it returns no rows if start is less than stop, and a step of zero is an error. Because the result is an ordinary row set, you can join it to a table or feed it to INSERT ... SELECT to create test rows without any loop.
Repeat a step with a recursive CTE
A recursive common table expression is the closest thing to a loop inside a single SQL statement. It has a starting query, then UNION ALL, then a recursive term that refers to the CTE itself. The PostgreSQL documentation uses this example to add the integers 1 to 100:
WITH RECURSIVE t(n) AS (
VALUES (1)
UNION ALL
SELECT n+1 FROM t WHERE n < 100
)
SELECT sum(n) FROM t;
The result is 5050. The database evaluates the starting term, then re-runs the recursive term against the rows produced by the previous pass until a pass returns nothing. Here the WHERE n < 100 condition is the loop's exit test. Remove it and the query never terminates, so every recursive CTE needs a condition that eventually produces zero rows.
This form is also the usual tool for walking hierarchies such as an employee-manager table, where each pass fetches the next level down.
When to avoid a loop
A row-by-row loop does its work one statement per row. A single set-based statement describes the whole change and lets the database plan it as one operation. That is why the first question to ask is whether a loop is needed at all. Compare these two ways to give every order over 100 a 10% discount:
-- Loop: one UPDATE per row
FOR o IN SELECT order_id FROM orders WHERE amount > 100 LOOP
UPDATE orders SET amount = amount * 0.9 WHERE order_id = o.order_id;
END LOOP;
-- Set-based: one statement
UPDATE orders SET amount = amount * 0.9 WHERE amount > 100;
Both produce the same final data; the second is shorter and has no loop to get wrong. Reach for a loop when each iteration genuinely depends on the previous one, when you must call a procedure once per row, or when you are running an administrative task such as creating a list of tables. For batch-processing very large tables, a loop that handles a limited number of rows per pass can also keep each transaction small, though that is a deliberate design choice and not a default.
Quick reference
| Goal | PostgreSQL | SQL Server |
|---|---|---|
| Count from 1 to N | FOR i IN 1..N LOOP or generate_series(1, N) | WHILE @i <= @N with a counter |
| Visit each row | FOR r IN SELECT ... LOOP | Cursor with WHILE @@FETCH_STATUS = 0 |
| Exit early | EXIT | BREAK |
| Where it runs | Function, procedure or DO block | Batch, procedure or trigger |
If your loop does not work
A syntax error on FOR or LOOP usually means you are running PL/pgSQL syntax outside a function or DO block, or you are on a database that does not use PL/pgSQL. If a T-SQL loop hangs, check that the counter changes on every pass, or that the cursor's FETCH NEXT sits inside the loop. If a recursive CTE never ends, check that the recursive term eventually returns no rows. When none of these apply, run the loop with a small input first, such as 1..3, and print the variable on each pass.
Frequently asked questions
- Does SQL have a for loop?
- Not in an ordinary query. Loops come from the procedural extension of each database: PL/pgSQL in PostgreSQL has FOR, and Transact-SQL in SQL Server has WHILE but no FOR. In a plain SELECT you repeat work with a set-based statement, a recursive CTE or a row generator instead.
- How do I loop through rows in SQL?
- In PostgreSQL, use FOR target IN query LOOP inside a function or DO block. In SQL Server, declare a cursor and fetch from it inside a WHILE loop. Before doing either, check whether one UPDATE, INSERT ... SELECT or JOIN can do the same job for all rows at once.
- How do I generate numbers 1 to 10 in SQL without a loop?
- In PostgreSQL, run SELECT * FROM generate_series(1, 10). On any database that supports recursive common table expressions, a WITH RECURSIVE query that adds 1 until it reaches 10 gives the same rows.
- Can a loop in SQL run forever?
- Yes. A WHILE loop runs as long as its condition is true, so a condition that never becomes false never stops. A recursive CTE has the same risk if its recursive term never produces an empty result. Always make sure something changes on each pass, such as a counter that increases.