Granting privileges lets you give users permission to do specific actions in the database. This keeps your data safe and organized.
Granting privileges in MySQL
GRANT privilege_type ON database_name.table_name TO 'username'@'host';
privilege_type can be SELECT, INSERT, UPDATE, DELETE, ALL PRIVILEGES, etc.
database_name.table_name specifies where the privilege applies. Use * for all databases or tables.
GRANT SELECT ON mydb.* TO 'alice'@'localhost';
GRANT ALL PRIVILEGES ON *.* TO 'bob'@'%';
GRANT INSERT, UPDATE ON shop.products TO 'carol'@'192.168.1.10';
This creates a new user 'dave' with a password, grants him permission to read and add data in the 'orders' table of 'testdb', and then shows his privileges.
CREATE USER 'dave'@'localhost' IDENTIFIED BY 'password123'; GRANT SELECT, INSERT ON testdb.orders TO 'dave'@'localhost'; SHOW GRANTS FOR 'dave'@'localhost';
After granting privileges, sometimes you need to run FLUSH PRIVILEGES; to apply changes immediately.
Be careful granting ALL PRIVILEGES; it gives full control which can be risky.
Use specific privileges to follow the principle of least privilege for better security.
Granting privileges controls what users can do in the database.
You specify the user, the allowed actions, and where those actions apply.
Always grant only the permissions needed to keep data safe.