MySQL Roles By Examples

MySQL Roles By Examples

 Summary: in this tutorial, you will learn how to use MySQL roles to simplify the privilege managements.

Introduction to MySQL roles

Typically, you have multiple users with the same set of privileges. Previously, the only way to grant and revoke privileges to multiple users is to change the privileges of each user individually, which is time-consuming.

To make it easier, MySQL provided a new object called role. A role is a named collection of privileges.

Like user accounts, you can grant privileges to roles and revoke privileges from them.

If you want to grant the same set of privileges to multiple users, you follow these steps:

  • First, create a new role.
  • Second, grant privileges to the role.
  • Third, grant the role to the users.

In case you want to change the privileges of the users, you need to change the privileges of the granted role only. The changes will take effect to all users to which the role granted.

MySQL role example

First, create a new database named CRM, which stands for customer relationship management.

CREATE DATABASE crm;
Code language: SQL (Structured Query Language) (sql)

Next, use the crm database:

USE crm;
Code language: SQL (Structured Query Language) (sql)

Then, create customer table inside the CRM database.

CREATE TABLE customers( id INT PRIMARY KEY AUTO_INCREMENT, first_name VARCHAR(255) NOT NULL, last_name VARCHAR(255) NOT NULL, phone VARCHAR(15) NOT NULL, email VARCHAR(255) );
Code language: SQL (Structured Query Language) (sql)

After that, insert data into the customers table.

INSERT INTO customers(first_name,last_name,phone,email) VALUES('John','Doe','(408)-987-7654','john.doe@mysqltutorial.org'), ('Lily','Bush','(408)-987-7985','lily.bush@mysqltutorial.org');
Code language: SQL (Structured Query Language) (sql)

Finally, verify the insert by using the following SELECT statement:

SELECT * FROM customers;
Code language: SQL (Structured Query Language) (sql)
mysql role - sample table

Creating roles

Suppose you develop an application that uses the CRM database. To interact with the CRM database, you need to create accounts for developers who need full access to the database. In addition, you need to create accounts for users who need only read access and others who need both read/write access.

To avoid granting privileges to each user account individually, you create a set of roles and grant the appropriate roles to each user account.

To create new roles, you use CREATE ROLE statement:

CREATE ROLE crm_dev, crm_read, crm_write;
Code language: SQL (Structured Query Language) (sql)

The role name is similar to the user account that consists of two parts: the name and host:

role_name@host_name
Code language: SQL (Structured Query Language) (sql)

If you omit the host part, it defaults to ‘%’ that means any host.

Granting privileges to roles

To grant privileges to a role, you use GRANT statement. The following statement grants all privileges to crm_dev role:

GRANT ALL ON crm.* TO crm_dev;
Code language: SQL (Structured Query Language) (sql)

The following statement grants SELECT privilege to crm_read role:

GRANT SELECT ON crm.* TO crm_read;
Code language: SQL (Structured Query Language) (sql)

The following statement grants INSERTUPDATE, and DELETE privileges to crm_write role:

GRANT INSERT, UPDATE, DELETE ON crm.* TO crm_write;
Code language: SQL (Structured Query Language) (sql)

Assigning roles to user accounts

Suppose you need one user account as the developer, one user account that can have read-only access and two user accounts that can have read/write access.

To create new users, you use CREATE USER statements as follows:

-- developer user CREATE USER crm_dev1@localhost IDENTIFIED BY 'Secure$1782'; -- read access user CREATE USER crm_read1@localhost IDENTIFIED BY 'Secure$5432'; -- read/write users CREATE USER crm_write1@localhost IDENTIFIED BY 'Secure$9075'; CREATE USER crm_write2@localhost IDENTIFIED BY 'Secure$3452';
Code language: SQL (Structured Query Language) (sql)

To assign roles to users, you use GRANT statement.

The following statement grants the crm_rev role to the user account crm_dev1@localhost:

GRANT crm_dev TO crm_dev1@localhost;
Code language: SQL (Structured Query Language) (sql)

The following statement grants the crm_read role to the user account crm_read1@localhost:

GRANT crm_read TO crm_read1@localhost;
Code language: SQL (Structured Query Language) (sql)

The following statement grants the crm_read and crm_write roles to the user accounts crm_write1@localhost and crm_write2@localhost:

GRANT crm_read, crm_write TO crm_write1@localhost, crm_write2@localhost;
Code language: SQL (Structured Query Language) (sql)

To verify the role assignments, you use the SHOW GRANTS statement as the following example:

SHOW GRANTS FOR crm_dev1@localhost;
Code language: SQL (Structured Query Language) (sql)

The statement returned the following result set:

As you can see, it just returned granted roles. To show the privileges that roles represent, you use the USING clause with the name of the granted roles as follows:

SHOW GRANTS FOR crm_write1@localhost USING crm_write;
Code language: SQL (Structured Query Language) (sql)

The statement returns the following output:

mysql role - show grants with using clause

Setting default roles

Now if you connect to the MySQL using the crm_read1 user account and try to access the CRM database:

>mysql -u crm_read1 -p Enter password: *********** mysql>USE crm;
Code language: SQL (Structured Query Language) (sql)

The statement issued the following error message:

ERROR 1044 (42000): Access denied for user 'crm_read1'@'localhost' to database 'crm'
Code language: SQL (Structured Query Language) (sql)

This is because when you granted roles to a user account, it did not automatically make the roles to become active when the user account connects to the database server.

If you invoke the CURRENT_ROLE() function, it will return NONE, meaning no active roles.

SELECT current_role();
Code language: SQL (Structured Query Language) (sql)

Here is the output:

+----------------+ | current_role() | +----------------+ | NONE | +----------------+ 1 row in set (0.00 sec)
Code language: SQL (Structured Query Language) (sql)

To specify which roles should be active each time a user account connects to the database server, you use the SET DEFAULT ROLE statement.

The following statement sets the default for the crm_read1@localhost account all its assigned roles.

SET DEFAULT ROLE ALL TO crm_read1@localhost;
Code language: SQL (Structured Query Language) (sql)

Now, if you connect to the MySQL database server using the crm_read1 user account and invoke the CURRENT_ROLE() function:

>mysql -u crm_read1 -p Enter password: *********** mysql> select current_role();
Code language: SQL (Structured Query Language) (sql)

You will see the default roles for crm_read1 user account.

+----------------+ | current_role() | +----------------+ | `crm_read`@`%` | +----------------+ 1 row in set (0.00 sec)
Code language: SQL (Structured Query Language) (sql)

You can test the privileges of crm_read account by switching the current database to CRM, executing a SELECT statement and a DELETE statement as follows:

mysql> use crm; Database changed mysql> SELECT COUNT(*) FROM customers; +----------+ | COUNT(*) | +----------+ | 2 | +----------+ 1 row in set (0.00 sec) mysql> DELETE FROM customers; ERROR 1142 (42000): DELETE command denied to user 'crm_read1'@'localhost' for table 'customers'
Code language: SQL (Structured Query Language) (sql)

It worked as expected. When we issued the DELETE statement, MySQL issued an error because crm_read1 user account has only read access.

Setting active roles

A user account can modify the current user’s effective privileges within the current session by specifying which granted role are active.

The following statement set the active role to NONE, meaning no active role.

SET ROLE NONE;
Code language: SQL (Structured Query Language) (sql)

To set active roles to all granted role, you use:

SET ROLE ALL;
Code language: SQL (Structured Query Language) (sql)

To set active roles to default roles that set by the SET DEFAULT ROLE statement, you use:

SET ROLE DEFAULT;
Code language: SQL (Structured Query Language) (sql)

To set active named roles, you use:

SET ROLE granted_role_1 [,granted_role_2, ...]
Code language: SQL (Structured Query Language) (sql)

Revoking privileges from roles

To revoke privileges from a specific role, you use the REVOKE statement. The REVOKE statement takes effect not only the role but also any account granted the role.

For example, to temporarily make all read/write users read-only, you change the crm_write role as follows:

REVOKE INSERT, UPDATE, DELETE ON crm.* FROM crm_write;
Code language: SQL (Structured Query Language) (sql)

To restore the privileges, you need to re-grant them as follows:

GRANT INSERT, UPDATE, DELETE ON crm.* FOR crm_write;
Code language: SQL (Structured Query Language) (sql)

Removing roles

To delete one or more roles, you use the DROP ROLE statement as follows:

DROP ROLE role_name[, role_name, ...];
Code language: SQL (Structured Query Language) (sql)

Like the REVOKE statement, the DROP ROLE statement revokes roles from every user account to which they were granted.

For example, to remove the crm_readcrm_write roles, you use the following statement:

DROP ROLE crm_read, crm_write;
Code language: SQL (Structured Query Language) (sql)

Copying privileges from a user account to another

MySQL treats user accounts like roles, therefore, you can grant a user account to another user account like granting a role to that user account. This allows you to copy privileges from a user to another user.

Suppose you need another developer account for the CRM database:

First, create the new user account:

CREATE USER crm_dev2@localhost IDENTIFIED BY 'Secure$6275';
Code language: SQL (Structured Query Language) (sql)

Second, copy privileges from the crm_dev1 user account to crm_dev2 user account as follows:

GRANT crm_dev1@localhost TO crm_dev2@localhost;
Code language: SQL (Structured Query Language) (sql)

In this tutorial, you have learned how to use MySQL roles to make it easier to manage privileges of user accounts.

ESL: Nouns

ESL: Nouns

Noun

A Noun is the name of a person, animal, place or thing.

There are four kinds of nouns:

1. The Common Noun 

A Common Noun is the name given in common to every person or thing of the same class or kind; such as, man, woman, boy, girl, town, country, book, desk.

2. The Proper Noun

A Proper Noun is the special name of a particular person or place; such as, Ramesh, Suresh, Sangeeta, Sanjana, Bangalore, India.

3. The Abstract Noun 

We can see the sun; we can touch a book; but can we see or touch courage? No. It is the name of something that we can only think of. Such a name is called an Abstract Noun.

An Abstract Noun is the name of something that we can only think of; such as, sweetness, kindness, darkness, weakness, pity, pain, hope, doubt, greed, childhood, misery, honesty, sleep, sickness, death, decency, hate, self-respect, Love, Sleep, strength, poverty, cruelty.

Abstract Nouns are nouns which cannot be identified by using our five senses (taste, touch, sight, hearing and smell).

4. The Collective Noun 

When a noun is the name of a number (or collection) of people or things considered as one, such as army, crowd, flock, fleet, it is called a Collective Noun.

examples: army, crowd, flock, fleet.

A Collective Noun is the name of a number of people or things considered as one.

Here are more examples of Collective Nouns:

  • a swarm of ants/flies/bees
  • a pack of wolves
  • a bunch of keys/flowers/grapes/bananas
  • a flight of stairs
  • a clump of trees
  • an anthology of stories/poems
  • a cluster of stars/grapes
  • a herd of cows/deer/elephants
  • a shoal of fish
  • a row of books/houses/trees
  • a band of musicians
  • a company of actors
  • a gang of thieves
  • a crew of sailors
  • a team of players
  • a crowd of people
  • a choir of singers
  • a sheaf of grains
  • a volley of bullets
  • a quiver of arrows
  • a jury of judges

EXERCISE (Write your answers in comment box)


EXERCISE 1

Underline the Common Nouns and circle the Proper Nouns in the sentences given below.

  1. Shilpi is her cousin.
  2. I bought some papers from People’s unit.
  3. Annie played with her brother.
  4. Mrs Bhatia brought her baby to the park.
  5. New Delhi is the capital of India.
  6. Paris is one of the most beautiful cities in Europe.
  7. Our new classmate came from Tamil Nadu.
  8. We went to the zoo in New Delhi.
  9. Araadhya likes her new dress.
  10. Saurabh has a bag of lollies.
  11. The twins went to a football match in Shimla.
  12. Did you know that President Obama was elected for two terms?
  13. The strawberries in the ice cream came from Vinayak Farms.
  14. Surabhi got a great score on her research report about Mohenjo-daro.
EXERCISE 2

Identify the underlined word in each sentence as a Proper or Common Noun. Write (P) for proper and (C) for common.

1. The Atlético de Kolkata is a good football team. ______
2. The Pune City shall play their first match tonight. ________
3. The family will eat together at the table. ________
4. The bear climbed up the tree. ________
5. I live in the state of Arunachal Pradesh. ________
6. We travelled down the Brahmaputra River. ________
7. The Chennaiyin FC is a good football team. ________
8. We will play basketball at the park. ________
9. I will walk home after school. ________
10. We saw a lion at the zoo. ________
11. We went to Lansdowne for vacation. ________
12. The Spelling Bee is an amazing championship. ________
13. We need to prepare for going back to school. ________

EXERCISE 3

Underline each Collective Noun in the following sentences.

1. The choir practised in the new auditorium.
2. I sing tenor in a quartet.
3. Everyone in the group received a door prize.
4. The team arrived early and went to the locker room.
5. As I watched, a flock of geese flew overhead.
6. The jury listened to the judge’s instructions.
7. During lunch today the committee will meet to plan fund-raising events.
8. Can you find your way through this thick grove of trees?
9. The cat and her litter found a home in my dog’s abandoned doghouse.
10. When Jared hit the beehive with a stick, a swarm of angry bees flew out.
11. For this short flight, the plane needs a crew of only three.

EXERCISE 4

Fill in the blanks with the correct form of Nouns.
1. He is a man of ……………………… (strong)
2. India got ………………………. from British rule in 1947. (free)
3. Every year on 15th of August, ………………………. awards are given to
the people by the prime minister. (brave)
4. He is on a ………………………. to Mecca. (pilgrim)
5. I have great …………………………. to welcome you. (please)
6. …………………………. is the best period of one’s life. (child)
7. ……………………….. of any kind should always be avoided. (waste)
8. As a parent my children’s …………. is of utmost importance to me. (safe)
9. As the sun went below the horizon ………. enveloped the planet. (dark)
10. There is no end to his ……………………….. (wicked)

EXERCISE 5
Pick out the Nouns in the following sentences and say whether they are
Common, Proper, Abstract, or Collective.
1. Mary had a little lamb.
2. My cousin has a dog, called Fido.
3. A cold wind blew last night.
4. The girl has a sweet voice.
5. The people who live in Holland are called the Dutch.
6. There was a large crowd in the street.
7. The child has caught a cold.
8. The elephant has great strength.
9. Are you speaking the truth?
10. Columbus discovered America.
11. Mumbai is a big city.
12. Solomon was famous for his wisdom.
13. He treats his children with great kindness.
14. Agra has many fine buildings.
15. Ashoka was a great king.
16. The wind and the sun had a quarrel.
17. Kolkata is on the banks of River Hooghly.
18. The girl showed great courage.
19. Ali gave his sister a great fright.
20. Our class consists of twenty pupils.
21. Without health, there is no happiness.
22. Our team is better than theirs

EXERCISE 6
Identify the Nouns in the following sentences.
1. Mrs D’Souza was planning a field trip to the Great Himalayan Valley in Uttarakhand.
2. Parts of the Great Himalayan Valley are still unexplored.
3. The giant formations produce feelings of awe in many visitors.
4. She captured our interest by describing cave-dwelling animals and fish.
5. Blindfish live in dark areas such as caves and underground streams.
6. They have nerves on their bodies that have a special sensitivity.
7. When tiny animals such as amphipods move, the blindfish sense the movement.
8. In this way, the fish can find and eat smaller animals without using sight.
9. A blindfish may eat its own offspring if it senses their movement.
10. These young fish stop moving when they feel something swimming nearby.
11. Mammoth Cave is part of the longest known cave system in the world.
12. Can you find your way through this thick grove of trees?