board logo
Posted by: drdread - 19 February 2025 12:28:38
Is there a script that would delete all non administrative users from my database in MySQL?

Posted by: sirclesadmin - 19 February 2025 12:29:52

Yes, you can use a MySQL script to delete all non-administrative users from your database. Assuming your users table has a column like role, user_type, or is_admin that distinguishes admin users from regular users, here’s how you can safely delete all non-admins.


SQL Script to Delete All Non-Admin Users

DELETE FROM users
WHERE role != 'admin';

or if your database uses a boolean is_admin column:

DELETE FROM users
WHERE is_admin = 0;

Safety Precautions Before Running the Script

  1. Backup your database: Run the following command to create a backup.
    mysqldump -u your_user -p your_database > backup.sql
    
  2. Check users before deleting: Run this query first to see which users will be deleted.
    SELECT * FROM users WHERE role != 'admin';
    
    or
    SELECT * FROM users WHERE is_admin = 0;
    
  3. Use Transactions for Reversibility:
    START TRANSACTION;
    DELETE FROM users WHERE role != 'admin';
    -- ROLLBACK; -- Uncomment this line if something goes wrong
    COMMIT;
    

Automating This with a Bash Script

If you want to automate the process using a shell script:

#!/bin/bash
mysql -u your_user -p'your_password' -D your_database -e "DELETE FROM users WHERE role != 'admin';"

⚠️ Warning: Storing passwords in scripts is insecure. Use MySQL config files or environment variables for better security.


Final Thoughts

  • Make sure your admin users are properly classified before running the script.
  • Test on a staging database before running on production.
  • If you need more advanced filtering (e.g., deleting users inactive for X days), let me know! 🚀