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';
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?
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With