MySQL - Show Privileges



The users in MySQL must have enough privileges to interact with the server. This is possible by assigning authentication details, like passwords to the users. In addition to this, operational or administrative privileges are granted separately if a user wants to interact with and operate on the data.

The MySQL SHOW Privileges

The MySQL SHOW PRIVILEGES Statement displays the list of privileges that are supported by the MYSQL server. The displayed list includes all static and currently registered dynamic privileges.

The information (returned list) contains three columns −

  • Privilege − Name of the privilege
  • Context − Name of the MySQL object for which the privilege is applicable.
  • Comment − A string value describing the purpose of the privilege.

Syntax

Following is the syntax to list out all privileges in a MySQL Server −

SHOW PRIVILEGES;

Example

Following query lists out all the privileges supported by the MySQL server −

SHOW PRIVILEGES

Output

After executing the above code, we get the following output −

PrivilegeContextComment
AlterTablesTo alter the table
Alter routineFunctions, ProceduresTo alter or drop stored functions/procedures
CreateDatabases, Tables, IndexesTo create new databases and tables
Create routineDatabasesTo use CREATE FUNCTION/PROCEDURE
Create roleServer AdminTo create new roles
Create temporary tablesDatabasesTo use CREATE TEMPORARY TABLE
Create viewTablesTo create new views
Create userServer AdminTo create new users
DeleteTablesTo delete existing rows
DropDatabases, TablesTo drop databases, tables, and views
Drop roleServer AdminTo drop roles
EventServer AdminTo create, alter, drop and execute events
ExecuteFunctions, ProceduresTo execute stored routines
FileFile access on serverTo read and write files on the server
Grant optionDatabases, Tables, Funcs, ProceduresTo give to other users those privileges you possess
IndexTablesTo create or drop indexes
InsertTablesTo insert data into tables
Lock tablesDatabasesTo use LOCK TABLES (together with SELECT privilege)
ProcessServer AdminTo view the plain text of currently executing queries
ProxyServer AdminTo make proxy user possible
ReferencesDatabases,TablesTo have references on tables
ReloadServer AdminTo reload or refresh tables, logs and privileges
Replication clientServer AdminTo ask where the slave or master servers are
Replication slaveServer AdminTo read binary log events from the master
SelectTablesTo retrieve rows from table
Show databasesServer AdminTo see all databases with SHOW DATABASES
Show viewTablesTo see views with SHOW CREATE VIEW
ShutdownServer AdminTo shut down the server
SuperServer AdminTo use KILL thread, SET GLOBAL, CHANGE MASTER, etc.
TriggerTablesTo use triggers
Create tablespaceServer AdminTo create/alter/drop tablespaces
UpdateTablesTo update existing rows
UsageServer AdminNo privileges - allow connect only
BINLOG_ENCRYPTION_ADMINServer Admin
AUDIT_ADMINServer Admin
ENCRYPTION_KEY_ADMINServer Admin
INNODB_REDO_LOG_ARCHIVEServer Admin
APPLICATION_PASSWORD_ADMINServer Admin
SHOW_ROUTINEServer Admin
BACKUP_ADMINServer Admin
BINLOG_ADMINServer Admin
CLONE_ADMINServer Admin
CONNECTION_ADMINServer Admin
SET_USER_IDServer Admin
SERVICE_CONNECTION_ADMINServer Admin
GROUP_REPLICATION_ADMINServer Admin
REPLICATION_APPLIERServer Admin
INNODB_REDO_LOG_ENABLEServer Admin
PERSIST_RO_VARIABLES_ADMINServer Admin
TABLE_ENCRYPTION_ADMINServer Admin
ROLE_ADMINServer Admin
REPLICATION_SLAVE_ADMINServer Admin
SESSION_VARIABLES_ADMINServer Admin
RESOURCE_GROUP_ADMINServer Admin
RESOURCE_GROUP_USERServer Admin
SYSTEM_USERServer Admin
SYSTEM_VARIABLES_ADMINServer Admin
XA_RECOVER_ADMINServer Admin

Listing Privileges Using a Client Program

Now, let us see how to retrieve/list all the privileges granted to the current MySQL user using a client program in programming languages like Java, PHP, Python, JavaScript, C++ etc.

Syntax

Following are the syntaxes −

To show all the privileges granted to an user, we need to pass the SHOW PRIVILEGES statement as a parameter to the query() function of the PHP mysqli library as −

$sql = "SHOW PRIVILEGES";
$mysqli->query($sql);

Following is the syntax to show all the privileges granted to the current user through a JavaScript program −

sql= "SHOW PRIVILEGES;"
con.query(sql, function (err, result) {
   if (err) throw err;
      console.log(result);
});

To show the privileges of the current user, we need to execute the SHOW PRIVILEGES statement using the JDBC executeQuery() function as −

String sql = "SHOW PRIVILEGES";
statement.executeQuery(sql);

Following is the syntax to show all the privileges granted to the current MySQL user through a Python program −

sql = f"SHOW GRANTS FOR '{username_to_show}'@'localhost'";
cursorObj.execute(sql);

Example

Following are the programs −

$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 = "SHOW PRIVILEGES"; if($result = $mysqli->query($sql)){ printf("PRIVILEGES found successfully...!"); printf("Lists are: "); while($row = mysqli_fetch_array($result)){ print_r($row); } } if($mysqli->error){ printf("Failed..!" , $mysqli->error); } $mysqli->close();

Output

The output obtained is as follows −

PRIVILEGES found successfully...!Lists are: Array
(
    [0] => Alter
    [Privilege] => Alter
    [1] => Tables
    [Context] => Tables
    [2] => To alter the table
    [Comment] => To alter the table
)
Array
(
    [0] => Alter routine
    [Privilege] => Alter routine
    [1] => Functions,Procedures
    [Context] => Functions,Procedures
    [2] => To alter or drop stored functions/procedures
    [Comment] => To alter or drop stored functions/procedures
)
Array
(
    [0] => Create
    [Privilege] => Create
    [1] => Databases,Tables,Indexes
    [Context] => Databases,Tables,Indexes
    [2] => To create new databases and tables
    [Comment] => To create new databases and tables
)
Array
(
    [0] => Create routine
    [Privilege] => Create routine
    [1] => Databases
    [Context] => Databases
    [2] => To use CREATE FUNCTION/PROCEDURE
    [Comment] => To use CREATE FUNCTION/PROCEDURE
)
Array
(
    [0] => Create role
    [Privilege] => Create role
    [1] => Server Admin
    [Context] => Server Admin
    [2] => To create new roles
    [Comment] => To create new roles
)
..........

 (
    [0] => REPLICATION_SLAVE_ADMIN
    [Privilege] => REPLICATION_SLAVE_ADMIN
    [1] => Server Admin
    [Context] => Server Admin
    [2] =>
    [Comment] =>
)
Array
(
    [0] => SENSITIVE_VARIABLES_OBSERVER
    [Privilege] => SENSITIVE_VARIABLES_OBSERVER
    [1] => Server Admin
    [Context] => Server Admin
    [2] =>
    [Comment] =>
)
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("--------------------------");

  sql = "SHOW PRIVILEGES";
  con.query(sql, function(err, result){
    if (err) throw err;
    console.log(result);
  });
});

Output

The output produced is as follows −

Connected!
--------------------------
[
  {
    Privilege: 'Alter',
    Context: 'Tables',
    Comment: 'To alter the table'
  },
.
.
.
  {
    Privilege: 'TELEMETRY_LOG_ADMIN',
    Context: 'Server Admin',
    Comment: ''
  }
]
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ShowPriv {
	public static void main(String[] args) {
		String url = "jdbc:mysql://localhost:3306/TUTORIALS";
		String user = "root";
		String password = "password";
		ResultSet rs;
		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 = "SHOW PRIVILEGES";
            rs = st.executeQuery(sql);
            System.out.println("All privileges: "); 
            while(rs.next()) {
            	String priv = rs.getNString(1);
            	System.out.println(priv);
            }
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}

Output

The output obtained is as shown below −

All privileges: 
Alter
Alter routine
Create
Create routine
Create role
Create temporary tables
Create view
Create user
Delete
Drop
Drop role
Event
Execute
File
Grant option
Index
Insert
Lock tables
Process
Proxy
References
Reload
Replication client
Replication slave
Select
Show databases
Show view
Shutdown
Super
import mysql.connector
# creating the connection object
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password'
)
username_to_show = 'newUser'
# Create a cursor object for the connection
cursorObj = connection.cursor()
cursorObj.execute(f"SHOW GRANTS FOR '{username_to_show}'@'localhost'")
privileges = cursorObj.fetchall()
print(f"Privileges for user '{username_to_show}' are:")
for grant in privileges:
    print(grant[0])
cursorObj.close()
connection.close()

Output

Following is the output of the above code −

Privileges for user 'newUser' are:
GRANT USAGE ON *.* TO `newUser`@`localhost`
GRANT SELECT, INSERT, UPDATE ON `your_database`.* TO `newUser`@`localhost`