Skip to main content
Database Design
CHAPTER 16 Beginner

Database Security | Access Control & SQL Injection Prevention

Updated: May 16, 2026
20 min read

# CHAPTER 16

Database Security and Access Control

1. Introduction

Data is the most valuable asset a company owns. If an application's servers go down for a day, the company loses money. If the database is hacked and 10 million user passwords are leaked, the company goes bankrupt. Database Security is not a feature you add at the end of development; it must be baked into the very foundation of the architecture. In this chapter, we will learn how to protect our data from the three main threats: external hackers, rogue internal employees, and application vulnerabilities.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the Principle of Least Privilege.
  • Create and manage Database User Accounts.
  • Implement Authorization using GRANT and REVOKE.
  • Defend against the devastating SQL Injection attack.
  • Understand the necessity of Data Encryption (Hashing).

3. The Principle of Least Privilege

The absolute golden rule of cybersecurity is the Principle of Least Privilege (PoLP). It states that an entity (a human or an application) should only be given the absolute minimum level of access necessary to perform its specific job, and nothing more.

If you connect your Node.js or PHP web server to the database using the root (Admin) database account, you have violated this principle catastrophically. If a hacker finds a bug in your web server, they instantly have full Admin control over the entire database!

4. Creating Users and Authorization (GRANT)

Instead of using the root account, Database Architects create specific, heavily restricted user accounts for different parts of the company.
sql
123456789
-- 1. Create a dedicated user account for the Web Application backend
CREATE USER 'webapp_user'@'localhost' IDENTIFIED BY 'SuperSecretPassword!';

-- 2. Grant it ONLY the permissions it needs to run the website!
-- It can Read, Insert, Update, and Delete rows.
GRANT SELECT, INSERT, UPDATE, DELETE ON ecommerce_db.* TO 'webapp_user'@'localhost';

-- Notice what we DID NOT grant: DROP or ALTER.
-- The web application physically CANNOT drop tables, even if hacked!

If an employee leaves the company, you instantly revoke their access:

sql
1
REVOKE ALL PRIVILEGES ON ecommerce_db.* FROM 'old_employee'@'localhost';

5. Preventing SQL Injection (SQLi)

SQL Injection is the oldest and most devastating database attack in existence. It occurs when a web application takes user input from a form (like a login box) and blindly stitches it into a raw SQL string.

*Vulnerable Backend Code:* "SELECT * FROM users WHERE email = '" + userinput + "';"

If the hacker types ' OR 1=1; DROP TABLE users; -- into the login box, the database evaluates the string, successfully logs the hacker in as an admin, and then deletes the entire users table!

The Architectural Fix: Prepared Statements (Parameterized Queries) Never, ever trust user input. When querying the database from a backend language, you must use Prepared Statements. This forces the database to compile the SQL structure *before* the user input is inserted, ensuring the database treats the input strictly as a text string, not as executable code.

6. Data Encryption (Hashing Passwords)

If your database is successfully breached, what happens to the data? If you store passwords as plain text (password123), the hackers now have the keys to your users' entire lives.

Architectural Rule: Never store raw passwords. Before the backend application sends the password to the database, it must pass it through a cryptographic Hash Function (like bcrypt or Argon2).

*What the database stores:* $2y$10$abcdefghijklmnopqrstuvwxyz1234567890 *(Even if the hackers steal the database, they cannot reverse the mathematically irreversible hash to find the real password).*

7. View-Based Security (Row/Column Level Security)

In Chapter 19 of the SQL Fundamentals course, we covered Views. Views are a powerful security mechanism. If you have an Employees table containing names and salaries, and the IT department needs to build a company directory, you do not give them access to the Employees table! You create a VIEW that only contains the names, and you GRANT SELECT permission strictly on the View. You have mathematically walled off the sensitive salary columns.

8. Mini Project: Securing a Production Environment

Let's lock down a new production server:
  1. 1. Network Layer: Configure the server firewall so port 3306 (MySQL) only accepts connections from the specific IP address of your Web Server. Block the entire public internet.
  1. 2. Access Layer: Disable the root remote login feature. Create a restricted webappuser with no DDL (DROP) permissions.
  1. 3. Application Layer: Refactor all backend Node.js code to use Prepared Statements, eradicating SQL Injection vulnerabilities.
  1. 4. Data Layer: Ensure all passwords are bcrypt hashed, and sensitive data like Credit Cards are encrypted at rest.

9. Common Mistakes

  • Shared Accounts: Creating one database user called devteam and sharing the password with 10 different developers. If data gets maliciously deleted, you have zero auditing capability to know who did it. Every human and every application must have a unique, distinct user account.

10. Best Practices

  • Regular Auditing: Utilize Database Triggers (Chapter 25 of SQL Fundamentals) to maintain strict, automated audit logs in high-security environments (e.g., logging exactly *who* updated a financial record and *when*).

11. Exercises

  1. 1. What cybersecurity principle dictates that a web application should never be connected to the database using the root (admin) account?
  1. 2. What cryptographic technique must be applied to user passwords before they are INSERTed into the database?

12. Database Design Challenges

A Junior Developer writes the following Python code to query the database: db.execute("SELECT * FROM users WHERE username = " + form
input). Identify the catastrophic vulnerability in this architectural pattern, and explain conceptually the industry-standard mechanism required to fix it. *(Answer: It is highly vulnerable to SQL Injection due to raw string concatenation. It must be fixed by utilizing Prepared Statements / Parameterized Queries, which separate the SQL compilation from the user data payload).*

13. MCQ Quiz with Answers

Question 1

When applying the Principle of Least Privilege to the database user account that connects your web application to your SQL server, which of the following SQL permissions should be strictly DENIED to that account?

Question 2

What is the fundamental, foolproof defense mechanism against all forms of SQL Injection (SQLi) attacks in modern software architecture?

14. Interview Questions

  • Q: Explain the mechanical step-by-step process of how an SQL Injection attack works. Why do Prepared Statements mathematically neutralize this threat?
  • Q: You are architecting a multi-tenant SaaS application. How would you utilize Database Views and the GRANT command to ensure that developers querying the database for analytics cannot accidentally view highly sensitive PII (Personally Identifiable Information) like Social Security Numbers?

15. FAQs

Q: Does encrypting the entire database protect me from SQL Injection? A: No. "Encryption at Rest" protects the hard drive if a thief physically breaks into the data center and steals the server. SQL Injection happens through the running application itself; the database decrypts the data for the hacker because the hacker successfully bypassed the logic!

16. Summary

You are now an Architect of Security. By strictly enforcing the Principle of Least Privilege, isolating application logic from raw data payloads via Prepared Statements, and managing granular user permissions, you can construct an impenetrable vault capable of securing enterprise-grade data.

17. Next Chapter Recommendation

We have learned all the individual pieces of architecture: Normalization, Indexes, Scaling, and Security. Now, we must synthesize them. In Chapter 17: Real-World Database Design Patterns, we will analyze the complete architectural blueprints of the world's most common software systems.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·