knowledge

Overview

SQL (Structured Query Language) is a programming language used to interact with relational databases. It stores, retrieves, and manipulates structured data organized in a table-based format. Understanding SQL is foundational for web development, database administration, and identifying injection vulnerabilities.


Terminology

TermDefinition
Relational DatabaseStores data in structured tables with defined relationships between them
NoSQLNon-relational database storing data in flexible, non-tabular formats
TableCollection of rows and columns storing structured data
ColumnDefines an attribute and its data type within a table
RowA single record within a table
Primary KeyUnique identifier for each record; only one per table
Foreign KeyLinks records between two tables; multiple allowed per table
DBMSDatabase Management System; software used to create and manage databases
CRUDCreate, Read, Update, Delete — the four basic database operations
ClauseSQL keyword used to filter or organize query results

Core Concepts

Database Types

TypeStructureBest For
Relational (SQL)Tables with rows and columnsStructured, consistent data
Non-Relational (NoSQL)Flexible non-tabular formatsUnstructured or user-generated data

Common DBMS: MySQL, MariaDB, MongoDB, SQLite

Relational databases link tables together through keys rather than storing all related data in one place — a users table and a posts table can each stay lean by referencing a shared id/user_id key instead of duplicating user details inside every post. This table-to-table relationship is called a schema.

Relational Database Table Relationships

NoSQL databases skip tables, rows, columns, and schemas entirely in favor of flexible storage models — useful when the data isn’t well-structured or the shape varies between records. Four common storage models:

  • Key-Value — every entry is a key paired with a value (string, JSON, or any object); resembles a dictionary/hash map
  • Document-Based — stores self-contained documents (e.g., JSON/BSON) rather than fixed rows
  • Wide-Column — rows can have a different set of columns from one another, unlike a fixed relational schema
  • Graph — stores nodes and the relationships between them, optimized for traversing connections

MongoDB is a common example of a document-based NoSQL database.

NoSQL Key-Value Storage Example

Key-Value example:

{
  "100001": {
    "date": "01-01-2021",
    "content": "Welcome to this web application."
  },
  "100002": {
    "date": "02-01-2021",
    "content": "This is the first post on this web app."
  }
}

The key is usually a string; the value can be a string, a nested object, or any class object — comparable to a dictionary literal in Python or PHP ({'key': 'value'}).

NoSQL databases are exploited differently than relational ones — NoSQL injection targets the query syntax of the specific NoSQL engine (e.g., MongoDB operator injection) rather than SQL syntax.

DBMS Core Features

FeatureDescription
ConcurrencyEnsures multiple simultaneous users can interact with the database without corrupting or losing data
ConsistencyKeeps data valid and consistent across the database despite concurrent interactions
SecurityFine-grained access control through authentication and permissions, preventing unauthorized viewing or editing
ReliabilityDatabases can be backed up and rolled back to a previous state after data loss or a breach
Structured Query LanguageSQL provides an intuitive, standardized syntax for interacting with the database

Architecture

A typical web application does not talk to the database directly:

  1. The application server receives user interactions (logins, comments, searches) via API calls or HTTP requests
  2. Middleware translates these events into the format the DBMS expects, using drivers/libraries specific to that DBMS
  3. The DBMS executes the requested operation (insert, retrieve, delete, update) and returns data or an error code

The application server and DBMS can run on the same host, but databases handling large amounts of data are typically hosted separately for performance and scalability.

Table Structure

  • Columns — define attributes and data types (string, integer, float, date)
  • Rows — individual records stored in the table
  • Primary Key — unique identifier per record; one per table
  • Foreign Key — references a primary key in another table to link data; multiple allowed

MySQL Usage

Connecting

mysql | mysql -u root -p

Database Operations

CommandDescription
CREATE DATABASE name;Create a new database
SHOW DATABASES;List all databases
USE name;Select a database to work with
DROP DATABASE name;Delete a database

Table Operations

CommandDescription
CREATE TABLE name (...);Create a new table
SHOW TABLES;List all tables in current database
DESCRIBE name;Show table structure and column types
ALTER TABLE name ADD col INT;Add a new column
ALTER TABLE name RENAME COLUMN old TO new;Rename a column
ALTER TABLE name MODIFY col DATE;Change a column’s data type
ALTER TABLE name DROP col;Remove a column
DROP TABLE name;Delete a table

Column Properties

Set when creating or altering a table to define constraints on individual columns:

PropertyEffect
NOT NULLColumn is required — cannot be left empty
UNIQUEEvery value inserted into the column must be distinct
DEFAULTSpecifies a fallback value if none is provided (e.g., DEFAULT NOW() for a timestamp)
AUTO_INCREMENTAutomatically increments an integer column (typically an ID) by one per new row
PRIMARY KEY (col)Uniquely identifies each record in the table

Example:

CREATE TABLE logins (
    id INT NOT NULL AUTO_INCREMENT,
    username VARCHAR(100) UNIQUE NOT NULL,
    password VARCHAR(100) NOT NULL,
    date_of_joining DATETIME DEFAULT NOW(),
    PRIMARY KEY (id)
);

CRUD Operations

OperationCommand
CreateINSERT INTO table VALUES (...);
Read (all)SELECT * FROM table;
Read (specific)SELECT col1, col2 FROM table;
UpdateUPDATE table SET col=value WHERE condition;
DeleteDELETE FROM table WHERE condition;

Clauses

ClausePurpose
FROMSpecifies the source table
WHEREFilters rows by condition
DISTINCTReturns only unique values
GROUP BYGroups rows sharing a value
ORDER BYSorts results (ASC/DESC)
HAVINGFilters grouped results

Examples: SELECT DISTINCT name FROM books; | SELECT * FROM books ORDER BY published_date ASC;

Operators

OperatorDescription
LIKEPattern matching
ANDAll conditions must be true
ORAt least one condition must be true
NOTNegates a condition
BETWEENValue within a range

Comparison Operators: Equal Sign != < > <= >=

Symbol equivalents: && (AND), || (OR), ! (NOT)

Operator Precedence

Order of evaluation, highest to lowest:

  1. Division (/), Multiplication (*), Modulus (%)
  2. Addition (+), Subtraction (-)
  3. Comparison (Equal Sign, >, <, <=, >=, !=, LIKE)
  4. NOT
  5. AND
  6. OR

Arithmetic inside a condition is resolved first, then comparisons, then logical operators top to bottom. In MySQL any non-zero value evaluates as true (typically returned as 1); 0 is false.

Functions

  • String: CONCAT() GROUP_CONCAT() SUBSTRING() LENGTH()
  • Aggregate: COUNT() SUM() MAX() MIN()

SQLite Usage

CommandDescription
sqlite3 example.dbOpen a SQLite database
.tablesList all tables
PRAGMA table_info(name);Show table structure
SELECT * FROM name;Query all records


References / Images

  • Relational Database Table Relationships
  • NoSQL Key-Value Storage Example
  • SQL syntax reference examples