Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete rows from all tables

Tags:

sql

mysql

I have a database with more than 100 tables. About 20 of them have a specific column, say column1.

Can I delete rows in all tables, where column1="abc", without specifying each table?

So I need something like this:

DELETE FROM [all tables] WHERE column1 = 'abc';
like image 729
Evgenij Reznik Avatar asked Apr 05 '16 15:04

Evgenij Reznik


People also ask

How do I delete a row in multiple tables?

The syntax also supports deleting rows from multiple tables at once. To delete rows from both tables where there are matching id values, name them both after the DELETE keyword: DELETE t1, t2 FROM t1 INNER JOIN t2 ON t1.id = t2.id; What if you want to delete nonmatching rows?

Which method is used to remove all rows in all tables in a dataset?

To delete all the rows in a table, always use TRUNCATE TABLE. TRUNCATE TABLE which is faster than a SQL delete statement and it uses fewer system and transaction-log resources.

Can you delete from multiple tables at once SQL Server?

You cannot DELETE from multiple tables with a single expression in SQL 2005 - or any other standard SQL for that matter. Access is the exception here. The best method to get this effect is to specify FOREIGN KEYS between the table with an ON DELETE trigger .


1 Answers

The easiest way may be the following:

SELECT 
CONCAT('DELETE FROM ',TABLE_NAME," WHERE column1 = 'abc';") comd
FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA = 'YOUR_DATABASE_NAME'
AND COLUMN_NAME ='column1';

This query will give you output like below:

DELETE FROM TABLE_1 WHERE column1 = 'abc';
DELETE FROM TABLE_2 WHERE column1 = 'abc';
DELETE FROM TABLE_3 WHERE column1 = 'abc';
DELETE FROM TABLE_4 WHERE column1 = 'abc';
.
.
.

Now copy these DELETE commands and execute all.


Note: In other way, you can write a stored program where you can turn these generated command strings into executable command/query through prepare statement.

But you can prefer the easiest way I've suggested above in order to bypass complexity.

like image 94
1000111 Avatar answered Oct 03 '22 03:10

1000111