2. Schema Design & Normalization

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

ConstraintPrimary Operational PurposeNullability BehaviorPhysical Indexing Impact
PRIMARY KEYUniquely identifies each tuple in the table.Implicitly and strictly NOT NULLAutomatically creates a Clustered Index (or Primary B-Tree)
FOREIGN KEYEnforces 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
UNIQUEPrevents duplicate non-null entries across column values.Permits multiple NULL entries (since NULL != NULL in SQL)Automatically creates a Unique Non-Clustered Index
NOT NULLPrevents missing/unknown values from being stored.Rejects NULL insertionsNone
CHECKValidates that column data satisfies a boolean expression.Evaluates expression; passes if TRUE or UNKNOWN (NULL)None
DEFAULTProvides fallback expression/literal if column is omitted on INSERT.Applied during missing INSERT valuesNone

πŸ”„ 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 value
  1. ON DELETE RESTRICT (Default): Throws a referential integrity violation error and blocks deletion of the parent row if any child rows reference it.
  2. ON DELETE CASCADE: Automatically deletes all child rows linked to the parent row being removed.
  3. ON DELETE SET NULL: Automatically updates the foreign key column in all linked child rows to NULL when 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 CategorySQL TypesStorage SizeEngineering Guidelines & Best Practices
Exact NumericINT, BIGINT, NUMERIC(p, s)4B, 8B, VariableUse 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 NumericFLOAT, DOUBLE PRECISION4B, 8BFast 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 StringVARCHAR(N), TEXTVariable (1 Byte + Length)VARCHAR(N) enforces maximum character bounds at application boundaries. TEXT stores arbitrary-length strings.
Temporal DataDATE, TIMESTAMP WITH TIME ZONE4B, 8BAlways store timestamps with explicit timezone information (TIMESTAMPTZ in PostgreSQL) to avoid cross-region UTC bugs.
Semi-StructuredJSONB, UUIDVariable, 16BJSONB 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    | Chess

2. 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, X must 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 MetricHighly Normalized Schemas (3NF)Denormalized Schemas (Star Schema)
Target Use CaseOLTP High-Concurrency Web ApplicationsOLAP Business Intelligence & Reporting
Write PerformanceExtremely Fast (Minimal data duplication)Slower (Multiple tables must be updated)
Read Query ComplexityComplex (Requires 5-10 table JOIN operations)Simple (Queries aggregate giant flattened Fact tables)
Storage FootprintCompact & MinimalLarger due to intentional column redundancy

❓ Conceptual Quizzes

Knowledge Check

What happens if a UNIQUE constraint is placed on a column containing multiple NULL values in standard SQL?

Knowledge Check

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.

On this page