SQL:SQL Relational Set Aggregation Methods vs Raw Cursor Loops Performance
SQL•Loops

SQL Relational Set Aggregation Methods vs Raw Cursor Loops Performance

Relational database engines are engineered for set-based mathematics, not procedural row-by-row cursor loops. Set-based aggregations (GROUP BY, window functions, and recursive CTEs) execute in vectorized, highly optimized C routines with indexing, outperforming row-by-row iterative cursors by orders of magnitude.

Syntax

-- Set-based vectorized aggregation (O(1) table scan) SELECT department_id, SUM(salary) FROM employees GROUP BY department_id; -- Rather than row-by-row FETCH NEXT FROM cursor loops!

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
GROUP BYSet OperatorVectorized partition algorithm executed natively by query engine.
Recursive CTERelational ConstructDeclarative set expansion replacing procedural WHILE loops.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing SQL locally:

-- 1. Worker tasks queue dataset
CREATE TABLE task_queue (
    task_id INTEGER PRIMARY KEY,
    worker_node TEXT,
    execution_ms INTEGER,
    status TEXT
);

INSERT INTO task_queue VALUES
    (1, 'node-alpha', 45,  'SUCCESS'),
    (2, 'node-alpha', 120, 'SUCCESS'),
    (3, 'node-beta',  310, 'FAILED'),
    (4, 'node-beta',  85,  'SUCCESS'),
    (5, 'node-gamma', 15,  'SUCCESS'),
    (6, 'node-gamma', 25,  'SUCCESS');

-- 2. Declarative set-based aggregation (Vectorized Processing)
SELECT 
    worker_node,
    COUNT(*) AS total_tasks,
    SUM(CASE WHEN status = 'SUCCESS' THEN 1 ELSE 0 END) AS successful_tasks,
    ROUND(AVG(execution_ms), 1) AS avg_duration_ms,
    MAX(execution_ms) AS peak_duration_ms
FROM task_queue
GROUP BY worker_node
ORDER BY avg_duration_ms DESC;
Expected Output:
worker_node  total_tasks  successful_tasks  avg_duration_ms  peak_duration_ms
-----------  -----------  ----------------  ---------------  ----------------
node-beta    2            1                 197.5            310             
node-alpha   2            2                 82.5             120             
node-gamma   2            2                 20.0             25              

How It Works: Step-by-Step

  • Lines 2-15: Creates and populates task_queue with distributed worker task durations.
  • Lines 18-26: Executes set-based GROUP BY aggregation without procedural cursors or cursor fetch loops.
  • Line 21: Demonstrates conditional aggregation inside SUM() to calculate success counts.

Key Concepts

  • Relational databases operate on sets of data simultaneously using optimized B-tree indices and parallel threads.
  • Procedural cursor loops (often referred to as RBAR: "Row By Agonizing Row") force query engines into iterative context switching.
  • Conditional aggregation via SUM(CASE WHEN ...) provides inline pivoted metrics in a single table scan.
  • Grouping by indexed columns allows the query planner to stream results without loading entire tables into temporary memory.

Common Mistake: Using procedural cursor loops instead of vectorized set operations

Migrating code from procedural languages often leads beginners to write cursor loops or WHILE loops in SQL, causing severe performance bottlenecks on large tables.

❌ Incorrect
DECLARE cursor FOR SELECT id FROM t; WHILE ... FETCH ... // Slow row-by-row execution!
✅ Correct
UPDATE t SET status = 'PROCESSED' WHERE condition; // Instant set-based execution

Related SQL Tutorials & Compiler

Run and test SQL on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

SQL Online Compiler