Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate through a list of rows returned from a select statement in SQL?

Tags:

sql

database

Given a SQL statement:

select id from myTable
where id = -1

How do I iterate through each of the results? I want to perform a specific operation for each result e.g (in pseudocode):

foreach (result from my statment)
{
  delete all rows from myOtherTable that has a value of result;
}

How would I write a SQL statement to do this?

N.B. The reason I want to do this is because the table whose row I want to delete is being referenced by other tables. So I thought that if I delete the rows from all that tables that reference this particular row and then delete the row everything will be fine.

like image 788
Draco Avatar asked Dec 18 '25 03:12

Draco


1 Answers

You don't need to iterate in SQL, you can write in one statement

DELETE FROM myOtherTable
WHERE myTableId IN (SELECT id FROM myTable WHERE id = -1)

EDIT:

After you complete the first delete you can then delete from the original table

DELETE FROM myTable WHERE id = -1
like image 150
Nathan Koop Avatar answered Dec 20 '25 16:12

Nathan Koop