Schema Design, Data Types & Normalization
Comprehensive reference for relational integrity constraints, SQL data types, referential integrity cascades, and normalization forms (1NF through BCNF) vs strategic denormalization.
π Relational Integrity Constraints
Constraints are declarative rules configured at schema definition time (CREATE TABLE / ALTER TABLE). The database storage engine enforces these rules on every INSERT, UPDATE, and DELETE operation to guarantee domain integrity and referential data validity across tables.
- Analogy: Building Blueprints & Inspection Codes.
- PRIMARY KEY: The unique National Identification / Fingerprint assigned to each resident.
- FOREIGN KEY: A parental guardianship paper linking a minor child to a verified parent record.
- UNIQUE: Passport numbersβno two residents can hold the exact same active passport string.
- CHECK: City structural safety codes (e.g., "Balcony railing height must be β₯ 42 inches").
CREATE TABLE departments (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(100) NOT NULL UNIQUE
);
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(100) NOT NULL,
salary NUMERIC(10, 2) CHECK (salary > 0),
dept_id INT,
email VARCHAR(150) UNIQUE,
status VARCHAR(20) DEFAULT 'ACTIVE',
CONSTRAINT fk_emp_dept FOREIGN KEY (dept_id)
REFERENCES departments(dept_id)
ON DELETE SET NULL
ON UPDATE CASCADE
);Constraint Mechanics Matrix
| Constraint | Primary Operational Purpose | Nullability Behavior | Physical Indexing Impact |
|---|---|---|---|
| PRIMARY KEY | Uniquely identifies each tuple in the table. | Implicitly and strictly NOT NULL | Automatically creates a Clustered Index (or Primary B-Tree) |
| FOREIGN KEY | Enforces referential integrity link to a parent table key. | Permits NULL values (unless explicitly marked NOT NULL) | Best practice: Manually add a Non-Clustered index to prevent full scans on joins |
| UNIQUE | Prevents duplicate non-null entries across column values. | Permits multiple NULL entries (since NULL != NULL in SQL) | Automatically creates a Unique Non-Clustered Index |
| NOT NULL | Prevents missing/unknown values from being stored. | Rejects NULL insertions | None |
| CHECK | Validates that column data satisfies a boolean expression. | Evaluates expression; passes if TRUE or UNKNOWN (NULL) | None |
| DEFAULT | Provides fallback expression/literal if column is omitted on INSERT. | Applied during missing INSERT values | None |
π Foreign Key Cascading Actions
When a parent row in a referenced table is deleted or updated, foreign key rules determine how child rows react:
Parent Row Deleted / Updated
β
βββββββββββββββββββββ¬ββββββββββββββ΄ββββββββββββββ¬ββββββββββββββββββββ
βΌ βΌ βΌ βΌ
ON DELETE RESTRICT ON DELETE CASCADE ON DELETE SET NULL ON DELETE SET DEFAULT
Blocks parent delete; Deletes linked child Sets child foreign Resets child foreign
throws FK error tuples automatically key field to NULL key to default valueON DELETE RESTRICT(Default): Throws a referential integrity violation error and blocks deletion of the parent row if any child rows reference it.ON DELETE CASCADE: Automatically deletes all child rows linked to the parent row being removed.ON DELETE SET NULL: Automatically updates the foreign key column in all linked child rows toNULLwhen the parent row is deleted.
π’ SQL Data Types Engineering Guide
Choosing proper physical column data types impacts disk storage footprint, CPU cache alignment, and indexing speed:
| Data Type Category | SQL Types | Storage Size | Engineering Guidelines & Best Practices |
|---|---|---|---|
| Exact Numeric | INT, BIGINT, NUMERIC(p, s) | 4B, 8B, Variable | Use BIGINT for auto-increment PKs expected to surpass 2 billion rows. Use NUMERIC(p,s) for financial monetary amounts to prevent floating-point rounding errors. |
| Approximate Numeric | FLOAT, DOUBLE PRECISION | 4B, 8B | Fast CPU calculations for scientific modeling, but prone to IEEE 754 floating-point precision loss (0.1 + 0.2 β 0.3). Never use for money! |
| Character String | VARCHAR(N), TEXT | Variable (1 Byte + Length) | VARCHAR(N) enforces maximum character bounds at application boundaries. TEXT stores arbitrary-length strings. |
| Temporal Data | DATE, TIMESTAMP WITH TIME ZONE | 4B, 8B | Always store timestamps with explicit timezone information (TIMESTAMPTZ in PostgreSQL) to avoid cross-region UTC bugs. |
| Semi-Structured | JSONB, UUID | Variable, 16B | JSONB stores decomposed binary JSON enabling fast GIN index queries. UUID provides globally unique 128-bit identifiers across distributed nodes. |
π Database Normalization (1NF to BCNF)
Normalization is the systematic process of organizing relational schema tables to eliminate data redundancy and prevent destructive database anomalies:
- Insertion Anomaly: Inability to insert data without adding dummy attributes in unrelated fields.
- Deletion Anomaly: Deleting one piece of data unintentionally wipes out completely unrelated critical information.
- Update Anomaly: Updating a single data entity requires modifying dozens of duplicate rows across the database.
- Analogy: Organizing your clothes closet. Instead of dumping shoes, shirts, coats, and socks into one giant unorganized bin (unnormalized table), you put shirts on hangers, shoes in shoe racks, and socks in labeled drawers (normalized relational tables).
Unnormalized Data βββΊ 1NF (Atomic Values) βββΊ 2NF (Remove Partial Dependencies)
β
BCNF (Strict Superkey) βββ 3NF (Remove Transitive Dependencies) ββ1. First Normal Form (1NF): Atomic Values
- Rule: Every column must contain indivisible atomic values. No repeating groups, arrays, or comma-separated strings stored inside single cells. Every row must be uniquely identifiable.
-- β VIOLATES 1NF: Multi-valued comma-separated string in hobbies cell
-- emp_id | emp_name | hobbies
-- 101 | Alice | "Reading, Swimming, Chess"
-- β
COMPLIES WITH 1NF: Decomposed into atomic tuples
-- emp_id | emp_name | hobby
-- 101 | Alice | Reading
-- 101 | Alice | Swimming
-- 101 | Alice | Chess2. Second Normal Form (2NF): Full Functional Dependency
- Rule: Table must be in 1NF, and every non-key attribute must depend on the entire primary key (eliminates partial functional dependencies in composite key tables).
3. Third Normal Form (3NF): Non-Transitive Dependencies
- Rule: Table must be in 2NF, and no non-key attribute can depend on another non-key attribute (eliminates transitive functional dependencies).
- Mantra: "Every non-key column must depend on the key, the whole key, and nothing but the key (so help me Codd)."
Transitive Dependency Violation:
Emp_ID (Primary Key) βββΊ Dept_ID (Non-Key) βββΊ Dept_Name (Non-Key)
Solution: Decompose into two separate tables:
1. employees: (emp_id [PK], emp_name, dept_id [FK])
2. departments: (dept_id [PK], dept_name)4. Boyce-Codd Normal Form (BCNF): Strict Superkey Rule
- Rule: A stricter refinement of 3NF. For every non-trivial functional dependency
X β Y,Xmust be a superkey (candidate primary key).
ποΈ Strategic Denormalization
While high normalization (3NF/BCNF) is mandatory for OLTP (Online Transaction Processing) systems to ensure high write performance and eliminate update anomalies, OLAP (Online Analytical Processing) data warehouses intentionally introduce denormalization (Star Schema / Snowflake Schema).
| Architectural Metric | Highly Normalized Schemas (3NF) | Denormalized Schemas (Star Schema) |
|---|---|---|
| Target Use Case | OLTP High-Concurrency Web Applications | OLAP Business Intelligence & Reporting |
| Write Performance | Extremely Fast (Minimal data duplication) | Slower (Multiple tables must be updated) |
| Read Query Complexity | Complex (Requires 5-10 table JOIN operations) | Simple (Queries aggregate giant flattened Fact tables) |
| Storage Footprint | Compact & Minimal | Larger due to intentional column redundancy |
β Conceptual Quizzes
What happens if a UNIQUE constraint is placed on a column containing multiple NULL values in standard SQL?
Why is using NUMERIC(10, 2) mandatory for financial salary data instead of FLOAT or DOUBLE PRECISION?
π» Practice Problems
Problem: Refactoring a Schema into 3NF
You are given an unnormalized orders table:
order_id (PK), customer_id, customer_name, customer_email, order_date, item_id, item_name, item_price
Identify the functional dependencies and refactor this single table into a clean 3NF schema structure.
SQL Engine Architecture & Command Taxonomy
Detailed technical breakdown of database query processing stages (lexer, parser, CBO optimizer, execution engine, buffer pool, WAL) and SQL command taxonomy (DDL, DML, DCL, TCL).
SQL Logical Execution Order & The NULL Trap
Master the exact 10-step logical execution sequence of SQL queries, 3-valued boolean logic, the NOT IN NULL hazard, and safe conditional expressions.