Manage Users, Roles, Grants, and Prevent SQL Injection
Learn SQL security and permissions in this beginner-friendly guide. Master creating users, assigning roles, using GRANT/REVOKE, securing views and stored procedures, and preventing SQL injection with parameterized queries.
1. Introduction
Database security is critical to protect sensitive data and ensure authorized access.
- SQL permissions allow administrators to control what users can view or modify.
- Security best practices prevent data breaches and SQL injection attacks.
Key Points:
- Roles simplify management by grouping users with similar privileges.
- Always limit access to only required operations.
- Use parameterized queries to prevent SQL injection.
2. Users and Roles
2.1 Create Users
2.2 Create Roles
2.3 Assign Users to Roles
3. GRANT and REVOKE Permissions
3.1 GRANT Permissions
3.2 REVOKE Permissions
Key Points:
- GRANT gives permissions; REVOKE removes them.
- Use principle of least privilege for security.
4. Views and Stored Procedures for Security
- Views can limit columns and rows users can access.
- Stored procedures allow controlled access to operations without exposing table structures.
Example – View for read-only employee data:
Grant access to view:
Stored Procedure Example:
Grant execute access:
5. SQL Injection Prevention
SQL injection occurs when malicious input alters SQL queries.
Unsafe Query Example:
Safe Query Using Parameterized Queries:
Tips:
- Use stored procedures with parameters.
- Avoid dynamic SQL with user input.
- Always validate and sanitize input.
6. Practical Exercises
- Create a user with read-only access to the Employees table.
- Create a role and assign multiple users to it.
- Grant SELECT permission on a view but not on the table.
- Create a stored procedure for department-based employee access and grant execute permission.
- Rewrite a vulnerable query using parameterized queries to prevent SQL injection.
7. Tips for Beginners
- Always follow the principle of least privilege.
- Use roles instead of assigning permissions individually.
- Limit direct table access; use views and stored procedures for operations.
- Parameterized queries are mandatory for user input.
- Regularly audit users and permissions to maintain database security.
Next Step: After mastering SQL security and permissions, the next module is Backup and Recovery in SQL, where you’ll learn full, differential, and transaction log backups, and how to restore databases safely.