mvp-ai's picture
download
raw
15.3 kB
id,category,option,best_for,avoid_when,tradeoffs,tags,last_verified
DB001,Primary Keys,UUID Primary Keys,"Distributed systems, public-facing IDs you don't want to reveal sequence/volume of, or multi-tenant apps merging data from multiple sources","High-volume tables where the extra 12 bytes vs a bigint and worse index locality genuinely matter at scale","Non-guessable and generatable client-side before insert (useful for optimistic UI), but larger and less index-friendly than sequential integers","uuid|primary-key|postgres",2026-07-03
DB002,Primary Keys,Auto-increment Integer / Bigint PK,"Internal tables where insertion order and compact indexes matter more than ID unguessability","IDs are ever exposed publicly and you don't want competitors/users inferring row counts or growth rate","Smallest, fastest-indexing PK type, but sequential and guessable — never use as the only access-control mechanism for a resource","serial|bigint|primary-key",2026-07-03
DB003,Primary Keys,UUID PK with a Separate Public Slug/Short-ID,"Public-facing resources needing both safe internal joins (UUID) and a short, shareable identifier (slug or nanoid) in URLs","Internal-only tables with no public URL surface — the extra column is unnecessary","Gets both worlds — DB-internal UUID stability and a clean public identifier — at the cost of maintaining two identifier columns","uuid|slug|public-id",2026-07-03
DB004,Delete Strategy,Soft Delete (deleted_at column),"Data with compliance/audit requirements, or where 'undo delete' is a real product feature (recoverable trash)","Table grows large and most queries would otherwise need to constantly filter deleted_at IS NULL — index that column if so","Recoverable and audit-friendly, but every query must remember to filter it out, and unique constraints need care (a 'deleted' row shouldn't block a new row with the same unique value)","soft-delete|audit|compliance",2026-07-03
DB005,Delete Strategy,Hard Delete,"Data with no compliance requirement to retain, or genuinely transient data (sessions, temp uploads)","Any regulatory requirement to retain records, or user-facing 'restore' expectations","Simpler queries (no filtering needed) and smaller tables over time, but truly unrecoverable — pair with backups as the only recovery path","hard-delete|simplicity",2026-07-03
DB006,Timestamps,created_at / updated_at on Every Table,"Every table, without exception — this is close to a universal default, not a situational choice","A genuinely immutable, append-only log table where 'updated_at' would never be non-null and is just noise — created_at alone is enough there","Enables debugging, auditing, and simple 'recently changed' queries for free; set updated_at via a DB trigger, not application code, so it can't be forgotten in one code path","timestamps|audit|universal-default",2026-07-03
DB007,Flexible Data,JSONB Column for Sparse/Variable Attributes,"Product attributes that vary wildly by category (e.g. e-commerce variants), user preferences blobs, or webhook payload archival","Fields that are queried/filtered/joined on frequently and consistently across all rows — those belong as real typed columns, not buried in JSONB","Schema flexibility without a migration per new field, and Postgres JSONB supports GIN indexing for reasonably fast queries — but loses type safety and makes ad-hoc reporting harder","jsonb|postgres|flexible-schema",2026-07-03
DB008,Flexible Data,Fully Normalized Typed Columns,"Core business entities where fields are consistent, frequently queried/filtered/joined, and benefit from DB-level type constraints","Attributes genuinely vary per row in ways no fixed schema captures well","Type safety, indexability, and constraint enforcement (NOT NULL, CHECK) at the DB level — the right default until you hit a real case for JSONB","normalization|typed-columns|constraints",2026-07-03
DB009,Enums & Lookups,Native Postgres ENUM Type,"A small, genuinely fixed set of values that rarely changes (e.g. `order_status`: pending/paid/shipped/cancelled)","Values will be added/removed/reordered by end users or admins at runtime, or the list is large/dynamic — use a lookup table instead","Type-safe and self-documenting in the schema, but adding a value is a migration and Postgres can't easily remove/reorder enum values once used","enum|postgres|status-fields",2026-07-03
DB010,Enums & Lookups,Lookup Table with Foreign Key,"Value sets that admins/users can extend over time (categories, tags, custom statuses per tenant)","A truly fixed, small, code-referenced set — a lookup table adds a join for no benefit there","Extensible without a schema migration and can carry metadata (display name, color, sort order) per value, at the cost of an extra join","lookup-table|foreign-key|extensible",2026-07-03
DB011,Associations,Many-to-Many Join Table,"Any true many-to-many relationship (users↔roles, posts↔tags, products↔categories)","One side is actually 1-to-many — don't add join-table complexity for a relationship that's really just a foreign key","Standard, well-indexed pattern; add a composite unique constraint on the two foreign keys to prevent duplicate associations","many-to-many|join-table|relational",2026-07-03
DB012,Associations,Polymorphic Association (type + id columns),"A comments/attachments/activity-log table that needs to reference many different resource types (post, product, user) generically","The set of referenceable types is small and stable — separate foreign key columns (nullable) or separate join tables per type are more DB-integrity-safe","Avoids a join table per referenceable type, but the database can't enforce a real foreign-key constraint across a polymorphic reference — integrity is app-enforced only","polymorphic|comments|activity-log",2026-07-03
DB013,Hierarchies,Adjacency List (parent_id self-reference),"Simple, shallow hierarchies (categories, org charts) where you mostly query 'direct children' or 'direct parent'","Deep trees where you frequently need 'all descendants' or 'all ancestors' in one query — that requires recursive CTEs here, which get expensive at depth","Simplest to implement and update (move a node = update one row), but full-subtree queries need a recursive CTE","hierarchy|adjacency-list|tree",2026-07-03
DB014,Hierarchies,Materialized Path / ltree,"Deep or frequently-queried hierarchies (comment threads, nested categories) where 'all descendants of X' needs to be fast and simple","Simple two-or-three-level hierarchies where adjacency list's simplicity is preferable","Postgres's native `ltree` type makes ancestor/descendant queries fast with a GiST index, at the cost of a path column that must be kept in sync on moves","ltree|hierarchy|postgres-extension",2026-07-03
DB015,Multi-Tenancy,Shared Tables + tenant_id + Row-Level Security,"SaaS apps on Supabase/Postgres where tenant isolation should be enforced at the database layer, not just in application code (see BE032)","Tenants need genuinely separate backup/restore schedules, independent scaling, or contractual data-residency guarantees per tenant","One schema to migrate and maintain; RLS makes 'a query can only ever see its own tenant's rows' a database-enforced guarantee instead of an app-layer convention that can be forgotten in one endpoint","multi-tenancy|rls|supabase|saas",2026-07-03
DB016,Multi-Tenancy,Schema-per-Tenant,"Mid-size B2B SaaS with a bounded, known tenant count where per-tenant customization or stronger isolation is worth the operational cost","Large numbers of tenants (hundreds+) — migrating N schemas on every deploy becomes the bottleneck","Stronger isolation and easier per-tenant backup/restore than shared tables, but every migration must run against every tenant schema","multi-tenancy|schema-per-tenant|b2b",2026-07-03
DB017,Multi-Tenancy,Database-per-Tenant,"Enterprise contracts requiring full data isolation, independent scaling, or data residency per customer","Most SaaS products, especially early-stage — this is the most operationally expensive isolation model and is rarely justified before real enterprise contracts require it","Maximum isolation and independent scaling per tenant, at meaningfully higher infrastructure and migration-orchestration cost","multi-tenancy|database-per-tenant|enterprise",2026-07-03
DB018,Search,tsvector Column + GIN Index for Full-Text Search,"In-app search over text content (posts, products, docs) where a dedicated search service (Elasticsearch/Algolia) would be overkill","Search needs typo-tolerance, faceting, or relevance tuning beyond what Postgres full-text search offers — reach for a dedicated search service instead","Full-text search without new infrastructure, generated/maintained via a trigger or generated column, good enough for most in-app search until you outgrow it","full-text-search|tsvector|postgres",2026-07-03
DB019,Indexing,B-tree Index on Foreign Keys and Frequent WHERE/JOIN Columns,"The default index type for equality/range lookups — apply to every foreign key column and every column used in WHERE/JOIN/ORDER BY","A column that's rarely queried directly — indexing everything 'just in case' slows down writes for no read benefit","Postgres does not auto-index foreign key columns — this is one of the most common missed-index causes of slow joins in production","indexing|btree|foreign-keys",2026-07-03
DB020,Indexing,Partial Index,"Queries that always filter on a condition (e.g. `WHERE deleted_at IS NULL`, `WHERE status = 'active'`) — index only the rows that matter","The filtered condition isn't stable/known in advance, or most rows match it anyway (little size benefit)","Smaller, faster index than indexing the whole column, tailored exactly to your hot-path query's WHERE clause","partial-index|postgres|performance",2026-07-03
DB021,Indexing,Composite Index Column Order,"Multi-column WHERE/ORDER BY queries — put the most selective / most frequently equality-filtered column first","A composite index where the query pattern doesn't consistently use the leading column — it won't be used efficiently then","Column order determines which query patterns can use the index (leftmost-prefix rule) — get it wrong and the index silently goes unused","composite-index|query-optimization|postgres",2026-07-03
DB022,Indexing,GIN Index for JSONB / Array / Full-Text Columns,"Querying inside a JSONB column, array containment checks, or full-text search (tsvector) — B-tree can't index these efficiently","Simple equality/range lookups on scalar columns — B-tree is the right (and default) choice there","Makes JSONB/array/full-text queries fast, but GIN indexes are larger and slower to update than B-tree — don't add them speculatively","gin-index|jsonb|full-text",2026-07-03
DB023,Constraints,Foreign Key ON DELETE Behavior (CASCADE vs RESTRICT vs SET NULL),"Every foreign key — decide explicitly per relationship: CASCADE for true ownership (delete a post's comments with it), RESTRICT to prevent accidental orphaning of important records, SET NULL for optional references","Never leave this as an unconsidered default — the default in most ORMs/migration tools is RESTRICT/NO ACTION, which silently blocks deletes if not chosen deliberately","Getting this wrong either orphans data silently (no cascade when you needed one) or blocks a delete operation mysteriously (restrict when you needed cascade)","foreign-key|cascade|referential-integrity",2026-07-03
DB024,Constraints,CHECK Constraints for Domain Validation,"Invariants that must always hold regardless of which application code path writes the row (e.g. `price >= 0`, `end_date > start_date`)","Validation that's genuinely business-logic-dependent and changes per context — that belongs in application code, not a rigid DB constraint","Database-enforced invariants can't be bypassed by a bug in one code path or a direct SQL fix that skips application validation","check-constraint|data-integrity|postgres",2026-07-03
DB025,Constraints,Unique Constraint at the Database Level (not just app-checked),"Any uniqueness requirement (email, slug, SKU) — enforce it as a DB unique constraint/index, never rely solely on an app-level 'check then insert'","Never skip the DB-level constraint even if app-level validation also exists — a race condition between two concurrent requests can defeat app-only checks","App-level 'check then insert' has a race condition window; a DB unique constraint is the only way to guarantee it under concurrent writes","unique-constraint|race-condition|data-integrity",2026-07-03
DB026,Specialized Patterns,Append-Only Event Log Table,"Audit trails, activity feeds, or event-sourcing-style systems where you need an immutable history of what happened, not just current state","The product only ever needs current state, with no audit/history requirement","Rows are never updated or deleted, only inserted — trivial to reason about and replay, but current-state queries require either a separate materialized view or reducing the log on read","event-log|audit-trail|event-sourcing",2026-07-03
DB027,Specialized Patterns,Slug Column for Public-Facing URLs,"Any resource with a public detail page where a human-readable URL (`/posts/how-to-ship-fast`) is preferable to a raw ID","Purely internal/API-only resources with no public URL surface","Better UX and SEO than a raw UUID/ID in the URL, at the cost of needing a uniqueness strategy (append a suffix on collision) and handling slug changes without breaking old links","slug|seo|public-urls",2026-07-03
DB028,Specialized Patterns,Money as Integer (Smallest Currency Unit),"Any column storing a monetary amount — store cents (or the smallest unit of the currency), never a float","Never store money as a floating-point type — floating-point rounding errors compound in financial calculations","Integer cents avoids floating-point rounding errors entirely; format to a display currency string only at the presentation layer, never store the formatted string","money|currency|data-types",2026-07-03
DB029,Specialized Patterns,Status/State Column Backed by an Explicit State Machine,"Any resource with a lifecycle (order: pending→paid→shipped→delivered) — define the allowed transitions explicitly in application code, backed by an enum/lookup column for the current state","A field that's just a flag with no lifecycle/transition rules — that's a plain boolean or enum, not a state machine","Prevents invalid transitions (shipped→pending) from ever being written, and makes 'what statuses exist and how do they flow' reviewable in one place instead of scattered across the codebase","state-machine|status|lifecycle",2026-07-03
DB030,Specialized Patterns,Row-Level Security Policies Colocated with Table Migrations,"Supabase/Postgres projects using RLS — write and version the RLS policy in the same migration file that creates or alters the table it protects","A table that intentionally has no RLS because it's accessed only via a trusted server-side service role — document that choice explicitly rather than leaving it ambiguous","Keeps the access-control rule next to the schema it governs instead of drifting apart in a separate, easy-to-forget migration","rls|supabase|migrations",2026-07-03

Xet Storage Details

Size:
15.3 kB
·
Xet hash:
05a1fed39bfd2bc6855b00d187c09e90edf46ab87e3421c3b8ffa35483d5d384

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.