0
0
MysqlHow-ToBeginner · 3 min read

How to Drop User in MySQL: Syntax and Examples

To drop a user in MySQL, use the DROP USER 'username'@'host'; command. This removes the user and their privileges from the database.
📐

Syntax

The DROP USER command removes a user account from MySQL. You must specify the username and the host from which the user connects.

  • 'username': The name of the user to remove.
  • 'host': The host or IP address the user connects from, often 'localhost'.

Both parts are required and enclosed in single quotes.

sql
DROP USER 'username'@'host';
💻

Example

This example shows how to drop a user named alice who connects from localhost. It deletes the user and all their privileges.

sql
DROP USER 'alice'@'localhost';
Output
Query OK, 0 rows affected (0.01 sec)
⚠️

Common Pitfalls

Common mistakes when dropping users include:

  • Not specifying the correct host, which causes MySQL to not find the user.
  • Trying to drop a user that does not exist, which results in an error.
  • Not having sufficient privileges to drop users.

To avoid errors when the user might not exist, use DROP USER IF EXISTS.

sql
/* Wrong: Missing host part */
DROP USER 'alice';

/* Right: Specify host */
DROP USER 'alice'@'localhost';

/* Safe: Avoid error if user does not exist */
DROP USER IF EXISTS 'alice'@'localhost';
📊

Quick Reference

CommandDescription
DROP USER 'user'@'host';Deletes the specified user and their privileges.
DROP USER IF EXISTS 'user'@'host';Deletes user only if they exist, avoiding errors.
SHOW GRANTS FOR 'user'@'host';Shows privileges of the user before dropping.

Key Takeaways

Use DROP USER 'username'@'host'; to remove a MySQL user.
Always specify both username and host to identify the user correctly.
Use DROP USER IF EXISTS to avoid errors if the user does not exist.
You need proper privileges to drop users in MySQL.
Check user privileges with SHOW GRANTS before dropping if needed.