Sunday, 28 February 2021

MYSQL how to remove all data from database

 1)MYSQL basic command 

mysql --user=user_name --password db_name

Can also specify password

mysql --user user_name --password mypassword db_name


https://dev.mysql.com/doc/refman/8.0/en/mysql.html


 2)To remove all records from all tables, need also to remove all foreign key constraints in database

SET FOREIGN_KEY_CHECKS = 0;
SET FOREIGN_KEY_CHECKS = 1;
https://www.mysqltutorial.org/mysql-disable-foreign-key-checks/
3)Use truncate to loop through all tables to remove them 
mysql -uroot -p<pass> -Nse 'show tables' database1 | while read table; do mysql -uroot -p<pass> database1 -e "truncate table $table"; done
https://stackoverflow.com/questions/32739365/mysql-how-to-clear-all-data-from-all-table-in-single-database

TRUNCATE TABLE statement removes all the data from a table 
and resets the auto-increment value to zero.
https://www.mysqltutorial.org/mysql-reset-auto-increment/#:~:text=The%20TRUNCATE%20TABLE%20statement%20removes,auto%2Dincrement%20value%20to%20zero.

4)Combine command with remove foreign_key_constraint and remove all data 
and set auto increment :

mysql -uroot -p<yourpwd> -Nse 'show tables' <yourDBName> | while read table; do mysql -uroot -p<yourpwd> <yourDBName> -e "SET FOREIGN_KEY_CHECKS = 0;truncate table $table;SET FOREIGN_KEY_CHECKS = 1"; done

No comments:

Post a Comment