Drop multiple tables in one shot in MySQL

MysqlSqlMultiple TablesDrop Table

Mysql Problem Overview


How to drop multiple tables from one single database at one command. something like,

> use test; 
> drop table a,b,c;

where a,b,c are the tables from database test.

Mysql Solutions


Solution 1 - Mysql

We can use the following syntax to drop multiple tables:

DROP TABLE IF EXISTS B,C,A;

This can be placed in the beginning of the script instead of individually dropping each table.

Solution 2 - Mysql

SET foreign_key_checks = 0;
DROP TABLE IF EXISTS a,b,c;
SET foreign_key_checks = 1;

Then you do not have to worry about dropping them in the correct order, nor whether they actually exist.

N.B. this is for MySQL only (as in the question). Other databases likely have different methods for doing this.

Solution 3 - Mysql

A lazy way of doing this if there are alot of tables to be deleted.

  1. Get table using the below
  • For sql server - SELECT CONCAT(name,',') Table_Name FROM SYS.tables;
  • For oralce - SELECT CONCAT(TABLE_NAME,',') FROM SYS.ALL_TABLES;
  1. Copy and paste the table names from the result set and paste it after the DROP command.

Solution 4 - Mysql

declare @sql1 nvarchar(max) 
SELECT @sql1 =
  STUFF(
         (
           select ' drop table dbo.[' + name + ']'

           FROM sys.sysobjects AS sobjects
           WHERE (xtype = 'U') AND (name LIKE 'GROUP_BASE_NEW_WORK_%')
           for xml path('')
        ),
     1, 1, '')

  execute sp_executesql @sql1

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKrunalView Question on Stackoverflow
Solution 1 - MysqlLeniel MaccaferriView Answer on Stackoverflow
Solution 2 - MysqlOrangeDogView Answer on Stackoverflow
Solution 3 - MysqlJavaughn JacksonView Answer on Stackoverflow
Solution 4 - Mysqluser4774666View Answer on Stackoverflow