Drop MySQL databases matching some wildcard?
To perform a massive cleanup in MySQL by dropping databases with a pattern, first, fetch the database names fitting the particular pattern and then pipe these results to a DROP DATABASE
command. Here's how you do it in a single line:
Replace user
and wildcard%
according to your needs. Be very careful—this will permanently erase every database that matches the wildcard.
Understand the command: Are you sure?
Before you turn on the ignition for this heavy artillery, make sure you're 100% certain about the target databases. Any destructive operation like this should be preceded by a data backup. Always test the commands in a sandbox first.
Automated deletion: The developer's Roomba
For more complex scenarios, we can utilize scripting to automate the dropping process. Here's a nifty PHP script that does just that:
This will retrieve a list of databases, match those against a complex pattern, and drop them after verification. Always ensure a backup precedes the execution, and run the script in a safe test environment beforehand.
Damage control: Safety nets
Once you're ready to deploy scripts for production, it's advisable to include the following safety mechanisms:
- Dialogue prompts for confirmation before dropping.
- Logging the drop commands for trail purposes.
- Using low-traffic periods for script execution to minimize the impact.
Other safe alternatives: When you're not a one-liner fan
If you're not comfortable using gutsy one-liners, you can opt to use graphical tools like MySQL Workbench, which provide intuitive interfaces.
With MySQL Workbench
With MySQL Workbench, use this:
Once you have the list, you can manually run DROP statements, thus maintaining stringent control over the deletion process. Use with caution!
With Python or Jython
A more versatile approach would be to use languages like Python or Jython. With these, you benefit from granular control over the databases, and you can implement additional logic, and safety checks.
Mind the special characters
Database names with special characters require special attention; they need to be escaped correctly. For instance, an underscore (_) is also a one-character wildcard in SQL.
Was this article helpful?