
- MySQL - Home
- MySQL - Introduction
- MySQL - Features
- MySQL - Versions
- MySQL - Variables
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Node.js Syntax
- MySQL - Java Syntax
- MySQL - Python Syntax
- MySQL - Connection
- MySQL - Workbench
- MySQL Databases
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Show Database
- MySQL - Copy Database
- MySQL - Database Export
- MySQL - Database Import
- MySQL - Database Info
- MySQL Users
- MySQL - Create Users
- MySQL - Drop Users
- MySQL - Show Users
- MySQL - Change Password
- MySQL - Grant Privileges
- MySQL - Show Privileges
- MySQL - Revoke Privileges
- MySQL - Lock User Account
- MySQL - Unlock User Account
- MySQL Tables
- MySQL - Create Tables
- MySQL - Show Tables
- MySQL - Alter Tables
- MySQL - Rename Tables
- MySQL - Clone Tables
- MySQL - Truncate Tables
- MySQL - Temporary Tables
- MySQL - Repair Tables
- MySQL - Describe Tables
- MySQL - Add/Delete Columns
- MySQL - Show Columns
- MySQL - Rename Columns
- MySQL - Table Locking
- MySQL - Drop Tables
- MySQL - Derived Tables
- MySQL Queries
- MySQL - Queries
- MySQL - Constraints
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Replace Query
- MySQL - Insert Ignore
- MySQL - Insert on Duplicate Key Update
- MySQL - Insert Into Select
- MySQL Indexes
- MySQL - Indexes
- MySQL - Create Index
- MySQL - Drop Index
- MySQL - Show Indexes
- MySQL - Unique Index
- MySQL - Clustered Index
- MySQL - Non-Clustered Index
- MySQL Operators and Clauses
- MySQL - Where Clause
- MySQL - Limit Clause
- MySQL - Distinct Clause
- MySQL - Order By Clause
- MySQL - Group By Clause
- MySQL - Having Clause
- MySQL - AND Operator
- MySQL - OR Operator
- MySQL - Like Operator
- MySQL - IN Operator
- MySQL - ANY Operator
- MySQL - EXISTS Operator
- MySQL - NOT Operator
- MySQL - NOT EQUAL Operator
- MySQL - IS NULL Operator
- MySQL - IS NOT NULL Operator
- MySQL - Between Operator
- MySQL - UNION Operator
- MySQL - UNION vs UNION ALL
- MySQL - MINUS Operator
- MySQL - INTERSECT Operator
- MySQL - INTERVAL Operator
- MySQL Joins
- MySQL - Using Joins
- MySQL - Inner Join
- MySQL - Left Join
- MySQL - Right Join
- MySQL - Cross Join
- MySQL - Full Join
- MySQL - Self Join
- MySQL - Delete Join
- MySQL - Update Join
- MySQL - Union vs Join
- MySQL Keys
- MySQL - Unique Key
- MySQL - Primary Key
- MySQL - Foreign Key
- MySQL - Composite Key
- MySQL - Alternate Key
- MySQL Triggers
- MySQL - Triggers
- MySQL - Create Trigger
- MySQL - Show Trigger
- MySQL - Drop Trigger
- MySQL - Before Insert Trigger
- MySQL - After Insert Trigger
- MySQL - Before Update Trigger
- MySQL - After Update Trigger
- MySQL - Before Delete Trigger
- MySQL - After Delete Trigger
- MySQL Data Types
- MySQL - Data Types
- MySQL - VARCHAR
- MySQL - BOOLEAN
- MySQL - ENUM
- MySQL - DECIMAL
- MySQL - INT
- MySQL - FLOAT
- MySQL - BIT
- MySQL - TINYINT
- MySQL - BLOB
- MySQL - SET
- MySQL Regular Expressions
- MySQL - Regular Expressions
- MySQL - RLIKE Operator
- MySQL - NOT LIKE Operator
- MySQL - NOT REGEXP Operator
- MySQL - regexp_instr() Function
- MySQL - regexp_like() Function
- MySQL - regexp_replace() Function
- MySQL - regexp_substr() Function
- MySQL Fulltext Search
- MySQL - Fulltext Search
- MySQL - Natural Language Fulltext Search
- MySQL - Boolean Fulltext Search
- MySQL - Query Expansion Fulltext Search
- MySQL - ngram Fulltext Parser
- MySQL Functions & Operators
- MySQL - Date and Time Functions
- MySQL - Arithmetic Operators
- MySQL - Numeric Functions
- MySQL - String Functions
- MySQL - Aggregate Functions
- MySQL Misc Concepts
- MySQL - NULL Values
- MySQL - Transactions
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - SubQuery
- MySQL - Comments
- MySQL - Check Constraints
- MySQL - Storage Engines
- MySQL - Export Table into CSV File
- MySQL - Import CSV File into Database
- MySQL - UUID
- MySQL - Common Table Expressions
- MySQL - On Delete Cascade
- MySQL - Upsert
- MySQL - Horizontal Partitioning
- MySQL - Vertical Partitioning
- MySQL - Cursor
- MySQL - Stored Functions
- MySQL - Signal
- MySQL - Resignal
- MySQL - Character Set
- MySQL - Collation
- MySQL - Wildcards
- MySQL - Alias
- MySQL - ROLLUP
- MySQL - Today Date
- MySQL - Literals
- MySQL - Stored Procedure
- MySQL - Explain
- MySQL - JSON
- MySQL - Standard Deviation
- MySQL - Find Duplicate Records
- MySQL - Delete Duplicate Records
- MySQL - Select Random Records
- MySQL - Show Processlist
- MySQL - Change Column Type
- MySQL - Reset Auto-Increment
- MySQL - Coalesce() Function
MySQL - Drop User
Dropping users in MySQL will remove a user's access and permissions on a specific database. This is performed by database administrators to maintain security and control over who can interact with the database system, ensuring that only authorized users can access and manipulate the data.
The MySQL Drop User Statement
You can drop/delete one or more existing users in MySQL using the DROP USER Statement. Once you delete an account, all privileges of it are deleted. To execute this statement, you need to have CREATE USER privilege.
Syntax
Following is the syntax of the DROP USER statement −
DROP USER [IF EXISTS] 'username'@'hostname';
Where, user_name is the name of the MySQL user you need to delete.
Example
Suppose, we have created a MySQL user account named 'TestUser' as shown below −
CREATE USER TestUser@localhost IDENTIFIED BY 'password1';
Following is the output obtained −
Query OK, 0 rows affected (0.04 sec)
You can verify the list of users using the following query −
SELECT user FROM MySQl.user;
The table will be displayed as shown below −
user |
---|
TestUser |
mysql.infoschema |
mysql.session |
mysql.sys |
newUser |
root |
sample |
Now, let us delete the 'TestUser' account created above using the DROP USER statement as shown below −
DROP USER TestUser@localhost;
After executing the above code, we can see the output as shown below −
Query OK, 0 rows affected (0.02 sec)
Verification
Once a table is dropped, if you verify the list of the users as shown below using the SELECT statement, you will find that its name is missing from the list −
SELECT user FROM MySQl.user;
The table obtained is as follows −
user |
---|
mysql.infoschema |
mysql.session |
mysql.sys |
newUser |
root |
sample |
Removing Multiple Users
You can also delete multiple users at once using the DROP ROLE statement. Roles are used to manage permissions and access control in a database system. By dropping a role, you revoke all privileges associated with that role. −
Example
Let us start by creating two roles 'MyAdmin' and 'MyDeveloper' −
CREATE ROLE 'MyAdmin', 'MyDeveloper';
The output obtained is as follows −
Query OK, 0 rows affected (0.01 sec)
Now, let us remove these roles using the DROP ROLE statement −
DROP ROLE 'MyAdmin', 'MyDeveloper';
This query will effectively delete both roles from the database −
Query OK, 0 rows affected (0.01 sec)
The IF EXISTS clause
If you try to drop a MySQL user that doesn't exist, an error will be generated. To address this issue, MySQL provides the IF EXISTS clause, which can be used with the DROP USER statement.
Hence, the IF EXISTS clause allows you to drop a user if they exist, and it handles situations where the specified user is not found in the database.
Example
In the below query, we are attempting to drop the 'demo' user. However, it results in an error because the user doesn't exist in the database −
DROP USER demo@localhost;
The output produced is as shown below −
ERROR 1396 (HY000): Operation DROP USER failed for 'demo'@'localhost'
If you use the IF EXISTS clause along with the DROP USER statement as shown below, the specified user will be dropped and if a user with the given name doesn't exist, the query will be ignored −
DROP USER IF EXISTS demo;
The output obtained is as follows −
Query OK, 0 rows affected, 1 warning (0.01 sec)
Dropping User Using a Client Program
In this section we are going to see various client programs to drop an existing user from MySQL.
Syntax
Following are the syntaxes to drop a MySQL user in various programming languages −
The MySQL PHP connector mysqli provides a function named query() to execute an SQL query in the MySQL database. To drop a user from a MySQL database, we need to execute the DROP USER statement using this function as −
$sql = "DROP USER 'username'@'localhost'"; $mysqli->query($sql);
To drop a user using a NodeJS program, we need to execute the DROP USER statement using the function named query() as −
sql= "DROP USER [IF EXISTS] user_name ..."; con.query(sql, function (err, result) { if (err) throw err; console.log(result); });
To drop an user in a MySQL database using Java program, we need to execute the DROP USER statement using the JDBC function named execute() as −
String sql = "DROP USER "USER_NAME'@'LOCALHOST'"; statement.execute(sql);
The MySQL Connector/Python provides a function namedexecute()to execute an SQL query in the MySQL database. To drop a user from a MySQL dataBase, we need to execute the DROP USER statement using this function as −
sql = "DROP USER 'UserName'@'localhost'"; cursorObj.execute(sql);
Example
Following are the client programs to drop an user in MySQL −
$dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'password'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass); if($mysqli->connect_errno ) { printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf('Connected successfully.
'); $sql = "DROP USER 'Revathi'@'localhost'"; if($mysqli->query($sql)){ printf("User dropped successfully...!"); } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();
Output
The output obtained is as follows −
User dropped successfully...!
var mysql = require('mysql2'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "Nr5a0204@123" }); //Connecting to MySQL con.connect(function (err) { if (err) throw err; console.log("Connected!"); console.log("--------------------------"); //Deleting Users sql = "DROP USER TestUser1@localhost;" con.query(sql); sql = "DROP USER TestUser2@localhost;" con.query(sql); //Listing the users after deleting sql = "select user from MySQl.user;" con.query(sql, function(err, result){ console.log("**List of Users after deleting:**") if (err) throw err console.log(result) }) });
Output
The output produced is as follows −
Connected! -------------------------- *List of Users after deleting:** [ { user: 'TestUser3' }, { user: 'TestUser4' }, { user: 'mysql.infoschema' }, { user: 'mysql.session' }, { user: 'mysql.sys' }, { user: 'root' }, { user: 'sample' } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class DropUsers { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/TUTORIALS"; String user = "root"; String password = "password"; try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection(url, user, password); Statement st = con.createStatement(); //System.out.println("Database connected successfully...!"); String sql = "DROP USER 'Vivek'@'localhost'"; st.execute(sql); System.out.println("User 'Vivek' dropped successfully...!"); }catch(Exception e) { e.printStackTrace(); } } }
Output
The output obtained is as shown below −
User 'Vivek' created successfully...!
import mysql.connector # creating the connection object connection = mysql.connector.connect( host='localhost', user='root', password='password' ) # Create a cursor object for the connection cursorObj = connection.cursor() cursorObj.execute("DROP USER 'UserNew'@'localhost'") print("User 'UserNew' is dropped successfully.") cursorObj.close() connection.close()
Output
Following is the output of the above code −
User 'UserNew' is dropped successfully.