You're not alone—coming from something like FoxPro, where row-by-row processing is built-in and intuitive, MySQL can feel a bit different since it's
set-based rather than
row-based. SQL, especially in MySQL, isn't designed to
iterate through rows in the same procedural way as older desktop databases. However, there are a few ways you can achieve similar behavior depending on your use case:
If possible, try to write a
single UPDATE statement that applies your logic to
all applicable rows at once:
UPDATE my_table
SET some_column = 'new_value'
WHERE some_condition;
This is faster, more efficient, and the intended way of working with SQL.
If You
Must Step Through Row by Row (Procedural Style)
DELIMITER //
Use a Stored Procedure with a Cursor
Cursors let you loop through rows one at a time in MySQL:
CREATE PROCEDURE update_rows()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE id_val INT;
-- Declare the cursor
DECLARE cur CURSOR FOR
SELECT id FROM my_table ORDER BY id;
-- Declare continue handler
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
-- Open the cursor
OPEN cur;
read_loop: LOOP
FETCH cur INTO id_val;
IF done THEN
LEAVE read_loop;
END IF;
-- Perform your update here
UPDATE my_table SET some_column = 'updated value' WHERE id = id_val;
END LOOP;
CLOSE cur;
END //
DELIMITER ;