Loops, cursors and result sets
A loop repeats work; a cursor walks query rows; a RESULTSET points to a query result that can be returned as a table.
Understand the idea
Use set-based SQL for ordinary aggregation or transformations whenever possible. Loops are useful when the workflow genuinely needs sequential actions, but running one SQL statement per row can introduce unnecessary work.
| Concept | What it means |
|---|---|
| FOR loop | Repeat over a bounded range or cursor rows. |
| Cursor | Read the rows of a query one at a time. |
| RESULTSET | Refer to a query’s result and return it with RETURN TABLE. |
A concrete example
Returns 6. The loop has three iterations.
Remember: Use iteration when the workflow requires it; do not replace clear relational operations unnecessarily.
Explain it step by step · full theory
Understand the idea
Use set-based SQL for ordinary aggregation or transformations whenever possible. Loops are useful when the workflow genuinely needs sequential actions, but running one SQL statement per row can introduce unnecessary work.
A bounded loop is easier to reason about than an unbounded loop. This first example adds 1, 2 and 3. A cursor example then sums two small rows to show the difference between iteration and a simple SUM query.
Follow the example
A cursor query normally executes when opened. A RESULTSET query executes when assigned. Cursor FOR loops manage opening and closing for this pattern; explicit OPEN/FETCH code must also close its cursor.
Returning TABLE(res) returns the result as rows. It does not create a permanent table or automatically save those rows for another session.
Words used in this lesson
- FOR loop
- Repeat over a bounded range or cursor rows.
- Cursor
- Read the rows of a query one at a time.
- RESULTSET
- Refer to a query’s result and return it with RETURN TABLE.
See how it works
Choose a step to explore the idea at your own pace.
Open the interactive explanation
Loops, cursors and result sets
Start with the requirement
A loop repeats work; a cursor walks query rows; a RESULTSET points to a query result that can be returned as a table.
Automatic playback is off for reduced motion. Select any step or use Previous and Next. Illustrations explain behavior; they are not live measurements.
Read the complete diagram explanation
- Start with the requirement
A loop repeats work; a cursor walks query rows; a RESULTSET points to a query result that can be returned as a table.
- Apply the rule
Use set-based SQL for ordinary aggregation or transformations whenever possible. Loops are useful when the workflow genuinely needs sequential actions, but running one SQL statement per row can introduce unnecessary work.
- Explain the result
Use iteration when the workflow requires it; do not replace clear relational operations unnecessarily.
Try the SQL or command
Read → predict → run in your learning environment → compare. You can also learn by reading without an account.
New to SQL? Where to run it and how to read it
A query is a question written in SQL. Snowflake runs it and returns a result table. This website shows examples; it does not connect to your account.
- No account yet? Read and predict the output first. Follow the account and Snowsight lesson when you are ready.
- For SQL practice, use a learning account in Snowsight and select an authorized role and warehouse. A role determines permissions; a warehouse supplies processing power. Follow the example’s database/schema setup when it refers to stored objects.
- Read the entire example, including comments beginning with
--. Run the selected statement or labeled block in the stated order. Examples labeled Python, shell or HTTP belong in that client, not in a SQL editor. - Compare values and row counts with the explained result. If an example deliberately causes an error, follow its rollback and cleanup steps before continuing.
- SELECT / FROM
- Choose the values to return / identify their input.
- VALUES / COLUMN1
- VALUES supplies tiny example rows. COLUMN1 means their first column, COLUMN2 their second.
- AS / WITH
- AS gives a result a readable name. WITH names a temporary query step within one statement.
- NULL / ::
- NULL means missing or unknown. The :: notation converts a value to a named data type.
- Session
- One connection and its settings. Keep related transaction steps in the same session.
- Database.schema.table
- A full address for stored data. It is separate from the warehouse that processes queries.
Need the L2_OBJECTS_LAB setup? Open the first database-object lesson →
Help with common practice errors
- No active warehouse: select a warehouse your role can use. Do not assume you need to create a new one.
- Object missing or not authorized: check the full name, required setup and active role. Ask the account owner for access if needed.
- Object already exists: setup may already have run. Read the current state or choose a fresh lab name consistently; do not add OR REPLACE blindly.
- Different result: check whether an earlier INSERT or UPDATE changed the data. VALUES examples provide their own fresh input for each statement.
Before running this lesson
Manual practice in an authorized Snowflake learning account. Run lesson 1 setup first and select L2_OBJECTS_LAB.M10_LAB and your authorized warehouse in each session. Use fresh object names; do not replace existing objects. Read whole scripting blocks before running them. The website does not execute commands.
Bound a numeric loop
EXECUTE IMMEDIATE $$
DECLARE total NUMBER DEFAULT 0;
BEGIN
FOR i IN 1 TO 3 DO
total := total + i;
END FOR;
RETURN total;
END;
$$;What to expect and why
Returns 6. The loop has three iterations.
Iterate through a cursor
EXECUTE IMMEDIATE $$
DECLARE
c CURSOR FOR SELECT COLUMN1 AS AMOUNT FROM VALUES (40),(60);
total NUMBER DEFAULT 0;
BEGIN
FOR rec IN c DO
total := total + rec.AMOUNT;
END FOR;
RETURN total;
END;
$$;What to expect and why
Returns 100. For a real total, SELECT SUM is usually clearer; this demonstrates cursor access.
Return a table-shaped result
CREATE PROCEDURE M10_SAMPLE_ROWS()
RETURNS TABLE (ID NUMBER, AMOUNT NUMBER) LANGUAGE SQL EXECUTE AS CALLER
AS $$
DECLARE res RESULTSET;
BEGIN
res := (SELECT COLUMN1::NUMBER AS ID,COLUMN2::NUMBER AS AMOUNT
FROM VALUES (1,40),(2,60) ORDER BY ID);
RETURN TABLE(res);
END;
$$;
CALL M10_SAMPLE_ROWS();What to expect and why
Returns two rows: 1/40 and 2/60.
Check your understanding
Choose an answer, then check your reasoning. This is practice, not a scored test.
Try it yourself
How many rows does M10_SAMPLE_ROWS return?
Compare your reasoning
Two rows, not one string containing a table.