2. Schema Design in Supabase
Designing Your Database the Supabase Way
Supabase projects are standard PostgreSQL databases. Schema design decisions here are permanent — a bad data model creates technical debt that compounds over years. This module teaches you to design schemas that are performant, secure, and aligned with how Supabase's API layer works.
When designing your schema, think about how the PostgREST API will expose your tables. Every table in the public schema gets an API endpoint automatically. Tables in other schemas are not exposed. This gives you a clean separation between public API tables and internal tables. The schema also determines how your RLS policies will work — policies filter rows based on the authenticated user. Your primary key choice affects performance, security, and URL safety. Foreign keys define relationships that PostgREST can traverse automatically. Indexes determine query performance. Constraints enforce data integrity. Understanding these design considerations will help you build a robust, secure application that performs well at scale.
The public Schema & Custom Schemas
By default, PostgREST exposes tables in the public schema. You can create additional schemas (e.g., private, audit) that are hidden from the auto-generated API, giving you an escape hatch for internal logic. This is a powerful security feature — tables in private schemas cannot be queried via the REST API even if an attacker somehow obtains your anon key. Use private schemas for audit logs, internal configuration, or any table that should only be accessed via Edge Functions or with the service_role key. You can still reference private tables in views that are exposed in the public schema. This gives you fine-grained control over your API surface.
-- Create a private schema for internal use (not exposed via API) CREATE SCHEMA private; -- Move a table to the private schema ALTER TABLE sensitive_logs SET SCHEMA private;
Primary Keys: UUID vs BIGSERIAL
Choosing the right primary key type is one of the most important schema decisions. UUIDs are globally unique and cannot be guessed sequentially, making them safer for public APIs. They're essential when syncing data across multiple systems or generating IDs client-side before insert. The gen_random_uuid() function is built into Postgres 13+ and requires no extension. BIGSERIAL/IDENTITY are auto-incrementing integers that are smaller in storage and slightly faster for joins. However, they're vulnerable to enumeration attacks if exposed in public URLs. Use BIGSERIAL for internal tables that don't need to be exposed via the API. For most Supabase applications, UUIDs are the recommended choice for public tables.
Globally unique, safe to expose in URLs. Cannot be guessed sequentially. Required when syncing data across multiple systems or generating IDs client-side before insert.
Auto-incrementing integer. Smaller storage, slightly faster joins. Vulnerable to enumeration attacks if exposed in public URLs. Best for internal tables.
-- Modern UUID primary key (no extension needed) CREATE TABLE profiles ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE );
Referencing auth.users
The Supabase Auth system stores users in a special auth.users table managed by GoTrue. Your public tables should reference this via a Foreign Key. The standard pattern is a profiles table in the public schema that extends the auth user. This table holds additional user data like full name, avatar URL, and role. The profiles table is linked to auth.users by a foreign key with ON DELETE CASCADE. A trigger automatically creates a profile when a new user signs up. This pattern keeps your public data separate from auth data while maintaining referential integrity. The SECURITY DEFINER attribute on the trigger function ensures it can insert into the profiles table regardless of RLS policies.
-- The canonical Supabase user extension pattern CREATE TABLE public.profiles ( id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE, full_name TEXT, role TEXT DEFAULT 'user' ); -- Auto-create a profile when a new user signs up CREATE OR REPLACE FUNCTION public.handle_new_user() RETURNS TRIGGER AS $$ BEGIN INSERT INTO public.profiles (id, full_name) VALUES (NEW.id, NEW.raw_user_meta_data->>'full_name'); RETURN NEW; END; $$ LANGUAGE plpgsql SECURITY DEFINER; CREATE TRIGGER on_auth_user_created AFTER INSERT ON auth.users FOR EACH ROW EXECUTE FUNCTION public.handle_new_user();
SECURITY DEFINER Functions
The SECURITY DEFINER attribute makes the function run with the privileges of the function's owner (usually postgres), not the calling user. This is essential for triggers that write to tables protected by RLS — the trigger itself needs elevated permissions to insert without policy interference.
Useful Column Conventions
Following consistent column conventions makes your schema easier to maintain and understand. Use TIMESTAMPTZ instead of TIMESTAMP for timezone-aware timestamps. Always include created_at and updated_at columns. The soft delete pattern uses a deleted_at column to mark records as deleted without actually removing them. A JSONB metadata column provides extensibility for arbitrary key-value data without schema migrations. The is_public boolean flag enables simple RLS policies for public vs private records. These conventions are widely used in the Supabase community and make your schema more maintainable.
- created_at TIMESTAMPTZ DEFAULT NOW() — Always use TIMESTAMPTZ (timezone-aware) not TIMESTAMP.
- updated_at TIMESTAMPTZ — Auto-update via a trigger using
moddatetimeextension. - deleted_at TIMESTAMPTZ — Soft delete pattern. Filter
WHERE deleted_at IS NULLin your views. - metadata JSONB DEFAULT
{}— Extensible field for arbitrary key-value data without schema migrations. - is_public BOOLEAN DEFAULT false — Simple flag for RLS policies to differentiate public vs. private records.
Knowledge Check
Ready to test your understanding of 2. Schema Design in Supabase?