14

Having read this link on RBAR and this, my understanding of RBAR amounts to this:

  1. Anything that have loops and cursors
  2. Anything that's not set based

I know this sounds kinda wholly which is why I am asking if anyone has a more elegant explanation as to what set-based programming is (within SQL context).

2 Answers 2

18

Set-based programming is based upon the mathematical concept of a set, and has operators that work on a whole set at a time. Procedural (RBAR) programming is based more on the traditional computer concepts of files and records. So to increase the salary of all employees in department X by 10%:

Set-based:

UPDATE employees SET salary = salary * 1.10 WHERE department = 'X';

Procedural (extreme example, pseudo-code):

OPEN cursor FOR SELECT * FROM employees;
LOOP
   FETCH cursor INTO record;
   EXIT WHEN (no more records to fetch);
   IF record.department = 'X' THEN
      UPDATE employees
      SET    salary = salary * 1.10
      WHERE  employee_id = record.employee_id;
   END IF
END LOOP
CLOSE cursor;

In the procedural version, only one employee row is being updated at a time; in the set-based version, all rows in the "set of employees in department X" are updated at once (as far as we are concerned).

Not sure this adds anything to what you will have already read in your links, but I thought I'd have a shot at it!

Sign up to request clarification or add additional context in comments.

3 Comments

Of course the set-based version is almost always faster as well usually by a lot.
Does the set method conjure a million magnets to alter the bytes of all records at once? Or does it also do it one by one in the end...
@JuanPerez LOL yes probably one by one under the covers. But not necessarily - there may be some parallelisation the optimiser can use that a developer can't access. More likely, it will just be faster because it doesn't have the overheads your code does. As your code will be a mixture of some procedural language and SQL, there will be "context switching" between each row. Set up an experiment to update 1 million rows using both methods, what is your result?
11

I will point out that set-based processing can involve loops. If you want to process in batches rather than tie up several tables while you load a million records into them in one set-based process, you can loop through batches of records, this is faster than a cursor which operates one row at a time and may be far better for your database than doing one giant insert statement.

Some RBAR processes don't look like cursors or loops either. These would include correlated subqueries and many user-defined functions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.