drdread
  • drdread
  • 100% (Exalted)
  • Advanced Member Topic Starter
3 days ago
Is there a script that would delete all non administrative users from my database in MySQL?
Sponsor

Want to thank us? Use: Patreon or PayPal or Bitcoins: bc1q4whppe29dw77rm4kv4pln0gqae4yjnxly0dny0hky6yhnafukzjsyrsqhk

All opinions expressed within these pages are sent in by members of the public or by our staff in their spare time, and as such do not represent any opinion held by sircles.net Ltd or their partners.


sirclesadmin
3 days ago

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! 🚀