MySQL: Check if the user exists and drop it

Solution 1:

This worked for me:

GRANT USAGE ON *.* TO 'username'@'localhost';
DROP USER 'username'@'localhost';

This creates the user if it doesn't already exist (and grants it a harmless privilege), then deletes it either way. Found solution here: http://bugs.mysql.com/bug.php?id=19166

Updates: @Hao recommends adding IDENTIFIED BY; @andreb (in comments) suggests disabling NO_AUTO_CREATE_USER.

Solution 2:

Since MySQL 5.7 you can do a DROP USER IF EXISTS test

More info: http://dev.mysql.com/doc/refman/5.7/en/drop-user.html

Solution 3:

To phyzome's answer (most highly voted one), it seems to me that if you put "identified by" at the end of the grant statement, the user will be created automatically. But if you don't, the user is not created. The following code works for me,

GRANT USAGE ON *.* TO 'username'@'localhost' IDENTIFIED BY 'password';
DROP USER 'username'@'localhost';

Hope this helps.