Database Review — Forge Skill
Overview
We use PostgreSQL via Supabase. Database design decisions are hard to change later, so they deserve careful review. Bad schema design, missing indexes, and unsafe migrations can cause outages.
Schema Design
Normalization
- Tables should be normalized to at least 3NF unless there's a documented performance reason for denormalization
- Avoid storing computed values that can be derived from other columns
- Use junction tables for many-to-many relationships
- Use JSONB columns sparingly — only when the schema is truly dynamic
Naming Conventions
- Tables:
snake_case, plural (users, blog_posts)
- Columns:
snake_case, singular (user_id, created_at)
- Primary keys:
id (UUID preferred)
- Foreign keys:
{referenced_table_singular}_id (e.g., user_id, post_id)
- Timestamps:
created_at, updated_at (with default values)
- Booleans:
is_ or has_ prefix (is_active, has_verified)
Required Columns
Every table should have:
id — UUID, primary key, default gen_random_uuid()
created_at — timestamptz, default now()
updated_at — timestamptz, updated via trigger or application code
Data Types
| Use |
Type |
Not This |
| IDs |
uuid |
serial, integer |
| Timestamps |
timestamptz |
timestamp (no timezone) |
| Money |
numeric(12,2) or bigint (cents) |
float, real |
| Status/enum |
PostgreSQL enum or text with check constraint |
Unconstrained text |
| JSON data |
jsonb |
json (not indexable) |
| Email |
citext or text with check |
varchar |
Index Strategy
When to Add Indexes
- Foreign key columns (PostgreSQL does NOT auto-index these)
- Columns used in WHERE clauses frequently
- Columns used in ORDER BY
- Columns used in JOIN conditions
- Unique constraints (these create indexes automatically)
When NOT to Add Indexes
- Small tables (< 1000 rows) — sequential scan is faster
- Columns with very low cardinality (e.g., boolean with 50/50 distribution)
- Write-heavy tables where read performance isn't critical
- Columns rarely used in queries
Index Types
-- B-tree (default, most common)
CREATE INDEX idx_posts_user_id ON posts (user_id);
-- Composite index (order matters — leftmost column first in queries)
CREATE INDEX idx_posts_user_date ON posts (user_id, created_at DESC);
-- Partial index (index only matching rows)
CREATE INDEX idx_posts_published ON posts (created_at)
WHERE is_published = true;
-- GIN index for JSONB
CREATE INDEX idx_users_metadata ON users USING GIN (metadata);
-- GiST index for full-text search
CREATE INDEX idx_posts_search ON posts USING GiST (to_tsvector('english', title || ' ' || body));
Index Review Checklist
N+1 Query Detection
The Problem
// BAD — N+1: 1 query for posts + N queries for authors
const posts = await supabase.from('posts').select('*');
for (const post of posts.data) {
const author = await supabase.from('users').select('*').eq('id', post.author_id).single();
}
// GOOD — join in a single query
const posts = await supabase
.from('posts')
.select('*, author:users(name, avatar_url)');
Signs of N+1 in Code Review
- Loops that contain database queries
Promise.all wrapping multiple identical queries with different IDs
useEffect that fetches related data after initial data loads
- Multiple sequential
.from() calls that could be a join
Fix Patterns
- Use Supabase's embedded selects (joins):
.select('*, relation(columns)')
- Use
IN queries: .in('id', arrayOfIds)
- Use database views for complex joins
- Use RPC functions for complex aggregations
Migration Safety
Safe Migration Checklist
Dangerous Migration Patterns
| Pattern |
Risk |
Safer Alternative |
DROP TABLE |
Data loss |
Rename to _deprecated_, drop later |
DROP COLUMN |
Data loss if column still used |
Add _deprecated suffix, drop after deploy |
ALTER COLUMN SET NOT NULL on existing data |
Fails if NULLs exist |
Add default, backfill, then add constraint |
CREATE INDEX on large table |
Table lock |
CREATE INDEX CONCURRENTLY |
| Renaming columns |
Breaks existing queries |
Add new column, migrate data, drop old |
| Changing column type |
Data loss or lock |
Add new column, migrate, swap |
Query Patterns
Pagination
// GOOD — cursor-based pagination
const { data } = await supabase
.from('posts')
.select('*')
.order('created_at', { ascending: false })
.lt('created_at', cursor)
.limit(20);
// ACCEPTABLE — offset pagination (for small datasets or admin tools)
const { data, count } = await supabase
.from('posts')
.select('*', { count: 'exact' })
.range(offset, offset + limit - 1);
Soft Deletes
// If using soft deletes
const { data } = await supabase
.from('posts')
.select('*')
.is('deleted_at', null); // Don't forget to filter!
Aggregations
-- Use database functions for aggregations, not client-side
CREATE OR REPLACE FUNCTION get_user_stats(uid uuid)
RETURNS TABLE (
post_count bigint,
comment_count bigint,
total_likes bigint
) AS $$
SELECT
(SELECT count(*) FROM posts WHERE author_id = uid),
(SELECT count(*) FROM comments WHERE user_id = uid),
(SELECT coalesce(sum(likes), 0) FROM posts WHERE author_id = uid);
$$ LANGUAGE sql SECURITY DEFINER;
Review Severity
| Issue |
Severity |
| Migration drops data without backup plan |
P0 — BLOCKED |
| N+1 query on user-facing page |
P1 — High |
| Missing index on foreign key |
P1 — High |
| Unsafe migration (locks table, no rollback) |
P1 — High |
Using timestamp instead of timestamptz |
P2 — Medium |
Missing updated_at column |
P3 — Low |
| Using offset pagination on large table |
P2 — Medium |
| Denormalization without justification |
P2 — Medium |
1---2name: database-review3description: Database Review — Forge Skill4metadata:5 source: https://skillmd.com/skills/nickgallick/database-review6---7# Database Review — Forge Skill89## Overview1011We use PostgreSQL via Supabase. Database design decisions are hard to change later, so they deserve careful review. Bad schema design, missing indexes, and unsafe migrations can cause outages.1213## Schema Design1415### Normalization1617- Tables should be normalized to at least 3NF unless there's a documented performance reason for denormalization18- Avoid storing computed values that can be derived from other columns19- Use junction tables for many-to-many relationships20- Use JSONB columns sparingly — only when the schema is truly dynamic2122### Naming Conventions2324- Tables: `snake_case`, plural (`users`, `blog_posts`)25- Columns: `snake_case`, singular (`user_id`, `created_at`)26- Primary keys: `id` (UUID preferred)27- Foreign keys: `{referenced_table_singular}_id` (e.g., `user_id`, `post_id`)28- Timestamps: `created_at`, `updated_at` (with default values)29- Booleans: `is_` or `has_` prefix (`is_active`, `has_verified`)3031### Required Columns3233Every table should have:34- `id` — UUID, primary key, default `gen_random_uuid()`35- `created_at` — timestamptz, default `now()`36- `updated_at` — timestamptz, updated via trigger or application code3738### Data Types3940| Use | Type | Not This |41|-----|------|----------|42| IDs | `uuid` | `serial`, `integer` |43| Timestamps | `timestamptz` | `timestamp` (no timezone) |44| Money | `numeric(12,2)` or `bigint` (cents) | `float`, `real` |45| Status/enum | PostgreSQL `enum` or text with check constraint | Unconstrained `text` |46| JSON data | `jsonb` | `json` (not indexable) |47| Email | `citext` or `text` with check | `varchar` |4849## Index Strategy5051### When to Add Indexes5253- Foreign key columns (PostgreSQL does NOT auto-index these)54- Columns used in WHERE clauses frequently55- Columns used in ORDER BY56- Columns used in JOIN conditions57- Unique constraints (these create indexes automatically)5859### When NOT to Add Indexes6061- Small tables (< 1000 rows) — sequential scan is faster62- Columns with very low cardinality (e.g., boolean with 50/50 distribution)63- Write-heavy tables where read performance isn't critical64- Columns rarely used in queries6566### Index Types6768```sql69-- B-tree (default, most common)70CREATE INDEX idx_posts_user_id ON posts (user_id);7172-- Composite index (order matters — leftmost column first in queries)73CREATE INDEX idx_posts_user_date ON posts (user_id, created_at DESC);7475-- Partial index (index only matching rows)76CREATE INDEX idx_posts_published ON posts (created_at)77 WHERE is_published = true;7879-- GIN index for JSONB80CREATE INDEX idx_users_metadata ON users USING GIN (metadata);8182-- GiST index for full-text search83CREATE INDEX idx_posts_search ON posts USING GiST (to_tsvector('english', title || ' ' || body));84```8586### Index Review Checklist8788- [ ] Foreign keys have indexes89- [ ] Query patterns match index column order90- [ ] No duplicate or redundant indexes91- [ ] Partial indexes used where appropriate92- [ ] Index impact on write performance considered9394## N+1 Query Detection9596### The Problem9798```typescript99// BAD — N+1: 1 query for posts + N queries for authors100const posts = await supabase.from('posts').select('*');101for (const post of posts.data) {102 const author = await supabase.from('users').select('*').eq('id', post.author_id).single();103}104105// GOOD — join in a single query106const posts = await supabase107 .from('posts')108 .select('*, author:users(name, avatar_url)');109```110111### Signs of N+1 in Code Review112113- Loops that contain database queries114- `Promise.all` wrapping multiple identical queries with different IDs115- `useEffect` that fetches related data after initial data loads116- Multiple sequential `.from()` calls that could be a join117118### Fix Patterns119120- Use Supabase's embedded selects (joins): `.select('*, relation(columns)')`121- Use `IN` queries: `.in('id', arrayOfIds)`122- Use database views for complex joins123- Use RPC functions for complex aggregations124125## Migration Safety126127### Safe Migration Checklist128129- [ ] Migration is backwards-compatible (old code works with new schema)130- [ ] No `DROP COLUMN` without verifying the column is unused in all code131- [ ] No `ALTER COLUMN` that changes type in a way that loses data132- [ ] No `NOT NULL` constraint added to existing column without default value133- [ ] Large table migrations use batched operations or `CONCURRENTLY`134- [ ] Indexes created with `CONCURRENTLY` to avoid table locks135- [ ] Migration tested against production-like data volume136- [ ] Rollback plan exists137138### Dangerous Migration Patterns139140| Pattern | Risk | Safer Alternative |141|---------|------|-------------------|142| `DROP TABLE` | Data loss | Rename to `_deprecated_`, drop later |143| `DROP COLUMN` | Data loss if column still used | Add `_deprecated` suffix, drop after deploy |144| `ALTER COLUMN SET NOT NULL` on existing data | Fails if NULLs exist | Add default, backfill, then add constraint |145| `CREATE INDEX` on large table | Table lock | `CREATE INDEX CONCURRENTLY` |146| Renaming columns | Breaks existing queries | Add new column, migrate data, drop old |147| Changing column type | Data loss or lock | Add new column, migrate, swap |148149## Query Patterns150151### Pagination152153```typescript154// GOOD — cursor-based pagination155const { data } = await supabase156 .from('posts')157 .select('*')158 .order('created_at', { ascending: false })159 .lt('created_at', cursor)160 .limit(20);161162// ACCEPTABLE — offset pagination (for small datasets or admin tools)163const { data, count } = await supabase164 .from('posts')165 .select('*', { count: 'exact' })166 .range(offset, offset + limit - 1);167```168169### Soft Deletes170171```typescript172// If using soft deletes173const { data } = await supabase174 .from('posts')175 .select('*')176 .is('deleted_at', null); // Don't forget to filter!177```178179### Aggregations180181```sql182-- Use database functions for aggregations, not client-side183CREATE OR REPLACE FUNCTION get_user_stats(uid uuid)184RETURNS TABLE (185 post_count bigint,186 comment_count bigint,187 total_likes bigint188) AS $$189 SELECT190 (SELECT count(*) FROM posts WHERE author_id = uid),191 (SELECT count(*) FROM comments WHERE user_id = uid),192 (SELECT coalesce(sum(likes), 0) FROM posts WHERE author_id = uid);193$$ LANGUAGE sql SECURITY DEFINER;194```195196## Review Severity197198| Issue | Severity |199|-------|----------|200| Migration drops data without backup plan | P0 — BLOCKED |201| N+1 query on user-facing page | P1 — High |202| Missing index on foreign key | P1 — High |203| Unsafe migration (locks table, no rollback) | P1 — High |204| Using `timestamp` instead of `timestamptz` | P2 — Medium |205| Missing `updated_at` column | P3 — Low |206| Using offset pagination on large table | P2 — Medium |207| Denormalization without justification | P2 — Medium |