Skip to content

SQL Fundamentals | Databases - Wyatt's Notes

SQL is defined by ANSI/ISO standards (SQL-86, SQL-89, SQL-92, SQL:1999, SQL:2003, SQL:2006, SQL:2008, SQL:2011, SQL:2016, SQL:2019, SQL:2023). No database implements the full standard. PostgreSQL has the broadest standards compliance among open-source databases. MySQL diverges Significantly. SQLite implements a large subset but omits many features (e.g., RIGHT JOIN, FULL OUTER JOIN were added in 3.39.0, 2022).

When this document specifies behaviour, it defaults to PostgreSQL syntax unless otherwise noted.

DDL defines and modifies the database schema. These statements are transactional in PostgreSQL and SQLite but often auto-commit in MySQL.

CREATE TABLE employees (
emp_id SERIAL PRIMARY KEY,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL,
hire_date DATE NOT NULL DEFAULT CURRENT_DATE,
salary NUMERIC(10,2) NOT NULL CHECK (salary > 0),
department_id INTEGER REFERENCES departments(dept_id) ON DELETE SET NULL,
CONSTRAINT uq_email UNIQUE (email),
CONSTRAINT chk_salary_range CHECK (salary >= 30000 AND salary <= 1000000)
);

Key elements:

  • SERIAL (PostgreSQL) / AUTO_INCREMENT (MySQL) / INTEGER PRIMARY KEY (SQLite) for auto-generating keys
  • NOT NULL — the column must have a value
  • UNIQUE — no two rows can have the same value in this column
  • CHECK — an arbitrary boolean expression evaluated on insert/update
  • DEFAULT — value used when no explicit value is provided
  • REFERENCES — foreign key constraint with referential action
Type CategoryPostgreSQL TypesNotes
IntegersSMALLINT``INTEGER``BIGINTINTEGER is 4 bytes, BIGINT is 8 bytes
Fixed precisionNUMERIC(p,s)``DECIMAL(p,s)Exact arithmetic; NUMERIC(10,2) holds up to 99,999,999.99
Floating pointREAL``DOUBLE PRECISIONInexact; avoid for financial data
Variable stringVARCHAR(n)``TEXTVARCHAR with length is a constraint, not a storage optimisation in PostgreSQL
Fixed stringCHAR(n)Padded with spaces; rarely useful
BooleanBOOLEANTRUE``FALSE``NULL
Date/TimeDATE``TIME``TIMESTAMP``TIMESTAMPTZTIMESTAMPTZ stores UTC; always prefer it over TIMESTAMP
BinaryBYTEAVariable-length binary data
JSONJSON``JSONBJSONB is stored in decomposed binary form; faster to query
UUIDUUIDRequires the uuid-ossp or pgcrypto extension
ArrayINTEGER[]``TEXT[]PostgreSQL-specific extension
NetworkINET``CIDR``MACADDRPostgreSQL-specific; enforces valid IP/MAC formats