4 Hours

2. Schema Design & Data Integrity

Engineering

Designing Production-Ready Tables

Choosing the right data type is the difference between a database that scales and one that breaks under pressure. In this module, we explore Postgres's elite type system and how to use constraints to build a Self-Validating database.

Postgres Power Types

  • UUID: Universally Unique Identifiers. Unlike SERIAL (1, 2, 3), UUIDs are unguessable. This prevents attackers from guessing your user count or enumeration attacks (e.g., trying /api/users/1, /api/users/2).
  • JSONB: Binary JSON. This allows you to store unstructured data but still query it with GIN Indexes. It is significantly faster than standard JSON.
  • NUMERIC: The only safe type for money. Never use FLOAT or REAL for currency, as they have precision errors (0.1 + 0.2 != 0.3).
  • CITEXT: Case-insensitive text. Perfect for emails so that User@VoidX.com and user@voidxhq.com are treated as the same unique record.

Constraints: The Database Firewall

Constraints are rules that the database enforces at the hardware level. They ensure that bad data never enters your system, even if your frontend or backend code has a bug.

NOT NULL

Ensures a field is never empty. Mandatory for passwords and IDs.

UNIQUE

Prevents duplicate entries. Essential for usernames and emails.

CHECK

Runs custom logic. Example: CHECK (price > 0) or CHECK (length(bio) < 500).

FOREIGN KEY

Ensures a link to another table is valid. Prevents Orphaned data.

SQL
-- A Professional Schema Pattern
CREATE TABLE products (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name TEXT NOT NULL,
  sku TEXT UNIQUE NOT NULL,
  price NUMERIC(10, 2) CHECK (price > 0),
  metadata JSONB DEFAULT '{}'::jsonb,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

Step-by-Step: Adding a Constraint to an Existing Table

  1. Identify: Find the column that needs a rule (e.g., email).
  2. Validate: Ensure all current data follows the rule, or the command will fail.
  3. Apply: Use ALTER TABLE to add the rule.
  4. Test: Try to insert bad data to verify the database rejects it.
SQL
ALTER TABLE users 
ADD CONSTRAINT email_must_be_lowercase 
CHECK (email = LOWER(email));

Knowledge Check

Ready to test your understanding of 2. Schema Design & Data Integrity?

Back