SQL Fundamentals
Databases store and organize application data. Web applications commonly use databases for users, sessions, products, posts, permissions, logs, and configuration.
Understanding databases and SQL is important for web security because many critical vulnerabilities involve unsafe database queries, especially SQL injection.
What Is a Database?
A database is a structured collection of data designed for storage, retrieval, and management.
Examples of data stored in web application databases:
- User accounts
- Password hashes
- Blog posts
- Orders
- Messages
- API tokens
- Permissions
- Audit logs
Relational vs. Non-Relational Databases
Databases are commonly grouped into relational and non-relational systems.
| Type | Description | Examples |
|---|---|---|
| Relational / SQL | Stores data in tables with rows and columns | MySQL, PostgreSQL, MSSQL, SQLite |
| Non-relational / NoSQL | Stores data in flexible formats like documents or key-value pairs | MongoDB, Redis, Cassandra |
Relational databases are common in traditional web applications, authentication systems, and business applications.
Non-relational databases are common in flexible, high-scale, or document-heavy systems.
Tables, Rows, and Columns
A relational database organizes data into tables.
Example users table:
| id | username | role | |
|---|---|---|---|
| 1 | alice | alice@example.com | user |
| 2 | bob | bob@example.com | admin |
| Concept | Meaning |
|---|---|
| Table | Collection of related data |
| Column | Attribute or field |
| Row | One record |
| Cell | One value in a row |
Example:
Data Types
Columns have data types.
Common SQL data types:
| Type | Purpose |
|---|---|
INT |
Whole numbers |
VARCHAR |
Variable-length text |
TEXT |
Longer text |
BOOLEAN |
True/false values |
DATE |
Date value |
TIMESTAMP |
Date and time |
DECIMAL |
Precise numeric values |
Example:
Primary Keys
A primary key uniquely identifies each row in a table.
Example:
In this table, id uniquely identifies each user.
Primary keys should be:
- Unique
- Stable
- Not null
- Used to reference specific records
Foreign Keys
A foreign key links one table to another.
Example:
CREATE TABLE orders (
id INT PRIMARY KEY,
user_id INT,
total DECIMAL(10, 2),
FOREIGN KEY (user_id) REFERENCES users(id)
);
In this example:
This means each order belongs to a user.
Basic SQL Commands
SQL is used to create, read, update, and delete data.
| Action | SQL Command |
|---|---|
| Create data | INSERT |
| Read data | SELECT |
| Update data | UPDATE |
| Delete data | DELETE |
| Create structure | CREATE |
| Modify structure | ALTER |
| Remove structure | DROP |
SELECT
SELECT reads data from a table.
Select all columns:
Filter results:
INSERT
INSERT adds new data.
UPDATE
UPDATE modifies existing data.
Warning
Be careful with UPDATE statements. Without a WHERE clause, all rows may be modified.
DELETE
DELETE removes data.
Warning
Be careful with DELETE statements. Without a WHERE clause, all rows may be deleted.
WHERE Clauses
WHERE filters query results.
Common operators:
| Operator | Meaning |
|---|---|
= |
Equal |
!= |
Not equal |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal |
<= |
Less than or equal |
LIKE |
Pattern match |
IN |
Match a list |
AND |
Both conditions true |
OR |
Either condition true |
Example:
LIKE
LIKE searches for patterns.
Pattern symbols:
| Symbol | Meaning |
|---|---|
% |
Any number of characters |
_ |
One character |
ORDER BY
ORDER BY sorts results.
Descending order:
LIMIT
LIMIT restricts how many rows are returned.
Useful for:
- Pagination
- Testing queries
- Preventing huge result sets
JOIN
JOIN combines data from multiple tables.
Example tables:
Query:
This returns order data with the username attached.
Common Database Systems
| Database | Type | Notes |
|---|---|---|
| MySQL | Relational | Common in PHP/Linux stacks |
| PostgreSQL | Relational | Powerful open-source database |
| MSSQL | Relational | Common in Microsoft environments |
| SQLite | Relational | File-based, lightweight |
| MongoDB | NoSQL | Document-based |
| Redis | NoSQL | Key-value store, often in memory |
NoSQL Example
NoSQL databases may store records as JSON-like documents.
{
"_id": "507f1f77bcf86cd799439011",
"username": "alice",
"email": "alice@example.com",
"roles": ["user", "editor"]
}
NoSQL can be useful when data structure is flexible, but it still requires secure query handling.
SQL Injection
SQL injection happens when user input is inserted into a database query unsafely.
Vulnerable example:
If input is concatenated directly into the query, an attacker may alter the query logic.
Example malicious input:
Resulting query:
Security impact may include:
- Authentication bypass
- Data extraction
- Data modification
- Data deletion
- Privilege escalation
- Remote code execution in some cases
Preventing SQL Injection
The main defense is parameterized queries, also called prepared statements.
Instead of building a query by concatenating strings, the query structure and user values are separated.
Conceptual example:
Other defenses:
- Input validation
- Least-privilege database accounts
- Safe error handling
- Avoiding dynamic SQL when possible
- Web application firewall as defense-in-depth
- Logging and monitoring suspicious queries
Important
Escaping input manually is not a replacement for parameterized queries.
Password Storage in Databases
Applications often store password hashes in databases.
Bad:
Better:
Good password storage uses:
- Strong password hashing algorithm
- Unique salt
- Slow hashing function
- No plaintext passwords
- No reversible encryption for normal password storage
Recommended algorithms:
- Argon2
- bcrypt
- scrypt
- PBKDF2
Database Security Basics
Good database security includes:
- Strong authentication
- Least-privilege users
- Network restrictions
- Encrypted connections
- Backups
- Monitoring
- Secure password storage
- Patch management
- Avoiding public exposure
Example:
Web app database user should only have permissions needed by the app.
It should not be a database administrator account.
Useful SQL Examples
Create a table:
CREATE TABLE users (
id INT PRIMARY KEY,
username VARCHAR(50),
email VARCHAR(255),
role VARCHAR(20)
);
Insert data:
Read data:
Update data:
Delete data:
Join tables:
Quick Reference
| Concept | Meaning |
|---|---|
| Database | Organized data storage |
| Table | Collection of related records |
| Column | Attribute or field |
| Row | Single record |
| Primary key | Unique row identifier |
| Foreign key | Link to another table |
| SQL | Query language for relational databases |
| NoSQL | Flexible non-relational database style |
| SELECT | Read data |
| INSERT | Add data |
| UPDATE | Modify data |
| DELETE | Remove data |
| JOIN | Combine tables |
| SQL injection | Unsafe query manipulation through user input |
Notes to Remember
- Relational databases store data in tables.
- Rows are records; columns are fields.
- Primary keys uniquely identify records.
- Foreign keys create relationships between tables.
- SQL is used to query and manage relational data.
- NoSQL stores data in flexible formats like documents or key-value pairs.
- SQL injection happens when user input changes query logic.
- Parameterized queries are the main defense against SQL injection.
- Database accounts should follow least privilege.