How do you create a MySQL user for an application and give it permissions?
BeginnerHands-onMySQL
Answer
Short answer
Create a user with CREATE USER, give it only the permissions it needs on its own database with GRANT, and never let the application use the root account.
Step by step
-- Create a user that can connect from anywhere ('%') — or limit to a subnet like '10.0.%'
CREATE USER 'orders_app'@'%' IDENTIFIED BY 'Str0ng#Pass';
-- Give it access to its own database only
GRANT SELECT, INSERT, UPDATE, DELETE ON shop.* TO 'orders_app'@'%';
-- Check what it has
SHOW GRANTS FOR 'orders_app'@'%';
-- Remove access later if needed
REVOKE DELETE ON shop.* FROM 'orders_app'@'%';
DROP USER 'orders_app'@'%';
| Part | Meaning |
|---|---|
'orders_app'@'%' |
User orders_app, allowed to connect from any host (%) |
shop.* |
All tables in the shop database |
SELECT, INSERT, UPDATE, DELETE |
Read and write data — but not drop tables or create users |
Why this matters
If the app is hacked and it uses root, the attacker controls every database on the server. With a limited user, they can only touch the app's own data — this is the principle of least privilege.
What to say in the interview
"Each application gets its own MySQL user with CREATE USER, and GRANT gives it only the privileges it needs on its own database — usually SELECT, INSERT, UPDATE and DELETE. We restrict the host part to the app's network where possible, store the password in a secret, and never use root from applications."
Follow-up questions you may get
- What does
'user'@'localhost'mean? The user can only connect from the database server itself. - Do you need
FLUSH PRIVILEGES? Not after GRANT or CREATE USER; only if you edit the grant tables directly.
More on MySQL
How do you set up MySQL and log in to it?BeginnerHow do you create a database, a table and see data in MySQL?BeginnerHow do you back up and restore a MySQL database?BeginnerWhat is a relational database?BeginnerWhat is the difference between a database, a table, a row and a column?BeginnerHow do you check whether MySQL is running and which port it listens on?Beginner