Relational Schema Design & PostgreSQL Types

Relational Schema Design & PostgreSQL Types in Supabase: Designing an enterprise database in Supabase leverages PostgreSQL's rich type system, foreign keys,…

Designing an enterprise database in Supabase leverages PostgreSQL's rich type system, foreign keys, and internal authentication schemas.


The auth.users Integration Pattern

When users register via Supabase Auth, their credentials, emails, and provider metadata are inserted into the protected system schema auth.users. Client applications cannot query or join this schema directly via PostgREST.

The standard pattern is to maintain a companion public.profiles table that links to auth.users via a primary foreign key:

-- 1. Create a public profiles table linked to auth.users
CREATE TABLE public.profiles (
    id UUID REFERENCES auth.users(id) ON DELETE CASCADE PRIMARY KEY,
    username VARCHAR(30) UNIQUE NOT NULL,
    display_name VARCHAR(100),
    avatar_url TEXT,
    bio TEXT,
    website TEXT,
    created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,
    updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,

    CONSTRAINT username_length CHECK (CHAR_LENGTH(username) >= 3)
);

-- 2. Create index on username for instant lookups
CREATE INDEX idx_profiles_username ON public.profiles(LOWER(username));

Modern PostgreSQL Data Types

Data TypeEnterprise Use CaseBest Practice
UUIDPrimary and Foreign keysUse gen_random_uuid() as default
TIMESTAMPTZTimestamps with timezoneAlways use TIMESTAMPTZ instead of TIMESTAMP to avoid timezone offsets
JSONBUnstructured or semi-structured dataBinary JSON format; supports GIN indexing and indexing inner paths
NUMERIC(12, 2)Financial amounts, ledger balancesPrevents floating-point rounding errors
TEXTStrings of any lengthIn PostgreSQL, TEXT has identical performance to VARCHAR(n) without artificial length limits

JSONB Columns & Indexing

PostgreSQL's JSONB stores JSON in a decomposed binary format, allowing fast indexing and key queries:

CREATE TABLE product_catalog (
    id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
    title TEXT NOT NULL,
    attributes JSONB NOT NULL DEFAULT '{}'::jsonb,
    created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL
);

-- Example attributes payload:
-- {"color": "space_gray", "storage_gb": 512, "tags": ["electronics", "laptop"]}

-- Fast GIN (Generalized Inverted Index) on the JSONB column:
CREATE INDEX idx_products_attributes ON product_catalog USING GIN (attributes);

-- Querying inside JSONB in SQL:
-- Uses the @> (contains) operator which leverages the GIN index!
SELECT * FROM product_catalog 
WHERE attributes @> '{"storage_gb": 512}';

Database Migrations with the Supabase CLI

Professional workflows avoid manual table creation via the dashboard UI in favor of version-controlled SQL migrations:

# Install Supabase CLI
npm install -g supabase

# Initialize project
supabase init

# Generate a new migration file
supabase migration new create_profiles_and_posts

# Diff changes against your local or remote database
supabase db diff -f add_teams_table

# Push migrations to production
supabase db push

Exercises

  1. Write a DDL script creating an organizations table and an organization_members join table with role enforcement (OWNER, ADMIN, MEMBER).
  2. Implement a JSONB column on an events table with a GIN index and write a query searching for nested key-value pairs.
  3. Explain why ON DELETE CASCADE on id UUID REFERENCES auth.users(id) guarantees data compliance under GDPR when a user deletes their account.