CRM ER diagram and database schema

The CRM database schema is a DB Planner template with 24 tables, 216 columns and 59 relationships, free to use. Core tables include account_domains, accounts, activities, activity_links. It can be opened as an interactive ER diagram or exported as PostgreSQL, MySQL, or SQL Server DDL.

ER diagram of the CRM database schema, showing 24 tables and their relationships
FIG. 1: entity relationship diagram, 24 tables
Tables
24
Columns
216
Relationships
59
Category
SaaS
Exports
DBML, SQL, Prisma, C#
Price
Free

What this schema models

A complete CRM database design, built the way sales teams actually run a pipeline: 24 tables, 14 enums and 59 relationships covering users, teams and record ownership, campaigns and leads with a conversion record, accounts, email domains and contacts, configurable pipelines and stages, opportunities with buying committees and an append-only stage history, products, price books, line items and versioned quotes, and calls, emails, meetings, tasks and notes. THE FOUR DESIGN RULES 1. A LEAD is not a CONTACT. Leads are unqualified (form fills, badge scans, list imports) and live in their own table with a company name, not an account. Conversion writes one lead_conversions row naming the account, contact and optional opportunity the lead became, and the lead stays read-only so its source and campaign are credited with any revenue it wins. 2. Stage history is append-only, because forecasting depends on it. Every change to stage, amount, close date or forecast category writes a row carrying the full forecast state. "What did the Q3 commit look like on September 1?", stage conversion rates and slipped close dates become queries, not guesses. 3. Prices are snapshots. Products hold no price; price book entries do, per currency. Opportunity line items copy the list price and the negotiated unit price when added, and a sent quote is frozen: a change is a new version, and the old one is marked superseded. 4. Activities link to many records with real foreign keys. One meeting with two contacts about one deal at one account is one activity and four activity_links rows. Each link fills exactly one typed foreign key column, enforced by a CHECK, instead of a record_type plus record_id pair, so no link can dangle. DETAILS WORTH STEALING - Pipelines and stages are data. Each stage carries a default probability, forecast category and outcome (open, won, lost), so reports never parse stage names. - ownership_history records every reassignment, which settles commission disputes and answers "who owned this deal in Q2?" - account_domains matches incoming leads and logged emails to the right account by email domain. - Contacts carry a case-insensitive unique index on lower(email) as a duplicate guard. - Email consent is a timestamp (email_opted_out_at), not a boolean, so you can prove when it was withdrawn. - opportunity_contacts records each person's role on a deal (champion, economic buyer, blocker), because the same person plays different roles on different deals. WHAT YOU GET Clean DBML that imports directly into DB Planner, and a laid-out board with zones color-coded and framed: users and ownership, leads and campaigns, accounts and contacts, sales pipeline, products and quotes, and activities and notes. Every table carries a note. Postgres-flavoured types that port cleanly to MySQL or SQL Server. Useful for developers building a CRM or sales tool, and for students who need a realistic CRM ER diagram for a DBMS project. This is a schema design reference; territory, assignment and approval rules belong in your own business logic.

Tables (24)

Every table and its columns

teams

Sales teams. The hierarchy is what forecast roll-ups and pipeline reviews are grouped by.

Columns of the teams table
ColumnTypeConstraintsReferencesDescription
iduuidPK
namevarchar(120)not nulle.g. EMEA Mid-Market, Inside Sales
parent_team_iduuidFKteams.idTeams roll up into regions, so a forecast can be read at any level
manager_iduuidFKusers.id
created_attimestamptznot null, default `now()`

users

People who use the CRM. Every account, contact, lead and opportunity has an owner here.

Columns of the users table
ColumnTypeConstraintsReferencesDescription
iduuidPK
emailvarchar(254)unique, not null
full_namevarchar(200)not null
roleuser_rolenot null
team_iduuidFKteams.id
manager_iduuidFKusers.id
timezonevarchar(64)not null, default 'UTC'
created_attimestamptznot null, default `now()`
deactivated_attimestamptzReps leave; their records are reassigned, never orphaned or deleted

ownership_history

Who owned which record, and when. Exactly one of the four record columns is set (CHECK num_nonnulls(...) = 1). Commission disputes, territory moves and "who was working this deal in Q2?" are all answered here, because the owner_id on the record only knows the present.

Columns of the ownership_history table
ColumnTypeConstraintsReferencesDescription
iduuidPK
account_iduuidFKaccounts.id
contact_iduuidFKcontacts.id
lead_iduuidFKleads.id
opportunity_iduuidFKopportunities.id
from_user_iduuidFKusers.idNull for the first assignment
to_user_iduuidFK, not nullusers.id
changed_byuuidFKusers.idNull for assignment rules and round-robin routing
reasonvarchar(200)e.g. territory realignment, rep left, round-robin
changed_attimestamptznot null, default `now()`

Indexes: (account_id), (contact_id), (lead_id), (opportunity_id)

campaigns

Marketing efforts that produce leads: a webinar, a trade show, a paid search push.

Columns of the campaigns table
ColumnTypeConstraintsReferences
iduuidPK
namevarchar(200)not null
kindcampaign_kindnot null
owner_iduuidFK, not nullusers.id
starts_ondate
ends_ondate
budget_centsbigint
currencychar(3)not null
created_attimestamptznot null, default `now()`

campaign_members

Who a campaign reached. Exactly one of lead_id or contact_id is set, since campaigns target existing customers too.

Columns of the campaign_members table
ColumnTypeConstraintsReferences
iduuidPK
campaign_iduuidFK, not nullcampaigns.id
lead_iduuidFKleads.id
contact_iduuidFKcontacts.id
statuscampaign_member_statusnot null, default 'targeted'
first_responded_attimestamptz
created_attimestamptznot null, default `now()`

Indexes: (campaign_id, lead_id) unique, (campaign_id, contact_id) unique

leads

Unqualified interest, kept apart from contacts. Leads are noisy (form fills, badge scans, list imports) and most never convert; mixing them into contacts pollutes every customer report and count.

Columns of the leads table
ColumnTypeConstraintsReferencesDescription
iduuidPK
owner_iduuidFKusers.idNull while unassigned in the routing queue
first_namevarchar(100)
last_namevarchar(100)not null
emailvarchar(254)
phonevarchar(30)
job_titlevarchar(150)
company_namevarchar(200)Free text. A lead has a company NAME, not an account; the account is created or matched at conversion.
sourcelead_sourcenot null
campaign_iduuidFKcampaigns.idFirst-touch campaign, kept for attribution
statuslead_statusnot null, default 'new'
scoresmallintFit and engagement score, 0 to 100
disqualified_reasonvarchar(200)
created_attimestamptznot null, default `now()`

Indexes: (email), (owner_id, status)

lead_conversions

Where a qualified lead went. The lead row stays, read-only, so its source and campaign are credited with any revenue the opportunity later wins.

Columns of the lead_conversions table
ColumnTypeConstraintsReferencesDescription
lead_iduuidPK, FKleads.id
account_iduuidFK, not nullaccounts.id
contact_iduuidFK, not nullcontacts.id
opportunity_iduuidFKopportunities.idNull when the lead converted without a deal yet
created_accountbooleannot nullFalse when the lead was matched to an existing account
created_contactbooleannot null
converted_byuuidFK, not nullusers.id
converted_attimestamptznot null, default `now()`

accounts

Companies you sell to, partner with or compete against.

Columns of the accounts table
ColumnTypeConstraintsReferencesDescription
iduuidPK
namevarchar(200)not null
parent_account_iduuidFKaccounts.idSubsidiary to parent, for account hierarchies and roll-ups
owner_iduuidFK, not nullusers.id
typeaccount_typenot null, default 'prospect'
industryvarchar(100)
employee_countinteger
annual_revenue_centsbigint
websitevarchar(300)
billing_countrychar(2)ISO 3166-1 alpha-2. Territory rules key off it.
created_attimestamptznot null, default `now()`
updated_attimestamptznot null, default `now()`
deleted_attimestamptz

Indexes: (owner_id), (name)

account_domains

Email domains an account owns. New leads, contacts and logged emails are matched to accounts by domain; free-mail domains are excluded in app code.

Columns of the account_domains table
ColumnTypeConstraintsReferencesDescription
domainvarchar(253)PKLowercase, e.g. example.com
account_iduuidFK, not nullaccounts.id
is_primarybooleannot null, default false

contacts

Qualified people, usually at an account. Their role on a specific deal lives on opportunity_contacts.

Columns of the contacts table
ColumnTypeConstraintsReferencesDescription
iduuidPK
account_iduuidFKaccounts.idNull for an individual with no company
owner_iduuidFK, not nullusers.id
first_namevarchar(100)
last_namevarchar(100)not null
emailvarchar(254)
phonevarchar(30)
job_titlevarchar(150)
departmentvarchar(100)
email_opted_out_attimestamptzConsent is a timestamp, not a boolean, so you can prove when it was withdrawn
created_attimestamptznot null, default `now()`
updated_attimestamptznot null, default `now()`
deleted_attimestamptz

Indexes: (account_id), (`lower(email)`) unique

pipelines

A sales process. New business and renewals rarely share the same stages.

Columns of the pipelines table
ColumnTypeConstraintsReferencesDescription
iduuidPK
namevarchar(100)not nulle.g. New business, Renewals, Partner deals
is_defaultbooleannot null, default false
created_attimestamptznot null, default `now()`

pipeline_stages

Stages as DATA, not an enum, so sales ops can add, rename and reorder them per pipeline without a migration. Reports read outcome and forecast_category, never the stage name.

Columns of the pipeline_stages table
ColumnTypeConstraintsReferencesDescription
iduuidPK
pipeline_iduuidFK, not nullpipelines.id
namevarchar(100)not nulle.g. Discovery, Demo, Proposal, Negotiation, Closed won
positionsmallintnot null
probability_pctsmallintnot nullDefault win probability, 0 to 100, for weighted pipeline
forecast_categoryforecast_categorynot nullDefault bucket for deals entering this stage
outcomestage_outcomenot null, default 'open'Whether reaching this stage closes the deal

Indexes: (pipeline_id, position) unique, (pipeline_id, name) unique

opportunities

A deal: an amount, a close date and a stage. Only the current values live here; how they moved over time is in opportunity_stage_history.

Columns of the opportunities table
ColumnTypeConstraintsReferencesDescription
iduuidPK
account_iduuidFK, not nullaccounts.id
namevarchar(200)not nulle.g. Example Corp, 250 seats, FY27
owner_iduuidFK, not nullusers.id
pipeline_iduuidFK, not nullpipelines.id
stage_iduuidFK, not nullpipeline_stages.id
price_book_iduuidFKprice_books.idChosen when the first product is added; sets the currency
amount_centsbigintnot null, default 0Sum of line items, or entered by hand on a deal with no products yet
currencychar(3)not null
close_datedatenot nullExpected close date while open, actual once closed
probability_pctsmallintnot null
forecast_categoryforecast_categorynot nullStarts from the stage default; the rep may override it
next_stepvarchar(300)
lost_reasonvarchar(200)
created_attimestamptznot null, default `now()`
closed_attimestamptz

Indexes: (owner_id, close_date), (stage_id), (account_id)

opportunity_stage_history

Append-only. A row is written whenever the stage, amount, close date or forecast category changes, carrying the full forecast state after the change. "What did the Q3 commit look like on September 1?" is the latest row per opportunity at or before that instant. Stage conversion rates, deal velocity and slipped close dates all come from here; none of them can be rebuilt from the current row.

Columns of the opportunity_stage_history table
ColumnTypeConstraintsReferencesDescription
iduuidPK
opportunity_iduuidFK, not nullopportunities.id
from_stage_iduuidFKpipeline_stages.idNull on the first row, when the deal is created
to_stage_iduuidFK, not nullpipeline_stages.id
amount_centsbigintnot null
currencychar(3)not null
close_datedatenot null
probability_pctsmallintnot null
forecast_categoryforecast_categorynot null
changed_byuuidFKusers.id
changed_attimestamptznot null, default `now()`

Indexes: (opportunity_id, changed_at)

opportunity_contacts

The buying committee. The same person can be the champion on one deal and a blocker on the next.

Columns of the opportunity_contacts table
ColumnTypeConstraintsReferences
opportunity_iduuidFK, not nullopportunities.id
contact_iduuidFK, not nullcontacts.id
rolecontact_rolenot null
is_primarybooleannot null, default false

products

What you sell. Holds no price: prices live in price books.

Columns of the products table
ColumnTypeConstraintsReferencesDescription
iduuidPK
skuvarchar(60)unique, not null
namevarchar(200)not null
descriptiontext
familyvarchar(100)e.g. Platform, Add-ons, Services
billingbilling_frequencynot null
is_activebooleannot null, default true
created_attimestamptznot null, default `now()`

price_books

Price lists. A standard list per currency plus regional, partner or negotiated books.

Columns of the price_books table
ColumnTypeConstraintsReferencesDescription
iduuidPK
namevarchar(100)not nulle.g. Standard USD, Partner EUR, Education
currencychar(3)not null
is_standardbooleannot null, default falseOne standard book per currency
valid_fromdate
valid_todate
is_activebooleannot null, default true

price_book_entries

The list price of one product in one price book.

Columns of the price_book_entries table
ColumnTypeConstraintsReferences
iduuidPK
price_book_iduuidFK, not nullprice_books.id
product_iduuidFK, not nullproducts.id
list_price_centsbigintnot null
is_activebooleannot null, default true

Indexes: (price_book_id, product_id) unique

opportunity_line_items

Products on a deal, with prices snapshotted. A later price book change never moves a deal already in the forecast.

Columns of the opportunity_line_items table
ColumnTypeConstraintsReferencesDescription
iduuidPK
opportunity_iduuidFK, not nullopportunities.id
product_iduuidFK, not nullproducts.id
price_book_entry_iduuidFK, not nullprice_book_entries.id
quantitynumeric(12,2)not null
list_price_centsbigintnot nullSnapshot of the entry price when the line was added
unit_price_centsbigintnot nullThe price actually offered after negotiation
discount_pctnumeric(5,2)not null, default 0
total_centsbigintnot null
sort_ordersmallintnot null

quotes

A priced offer sent to the customer. Once sent it is never edited: a change is a new version, and the old one becomes superseded.

Columns of the quotes table
ColumnTypeConstraintsReferencesDescription
iduuidPK
opportunity_iduuidFK, not nullopportunities.id
quote_numbervarchar(30)unique, not nulle.g. Q-2026-00417
versionsmallintnot null, default 1
statusquote_statusnot null, default 'draft'
currencychar(3)not null
subtotal_centsbigintnot null
discount_centsbigintnot null, default 0
tax_centsbigintnot null, default 0
total_centsbigintnot null
valid_untildatenot null
created_byuuidFK, not nullusers.id
created_attimestamptznot null, default `now()`
sent_attimestamptz
accepted_attimestamptz

Indexes: (opportunity_id, version) unique

quote_line_items

Copied from the opportunity line items when the quote is generated, then frozen with it. The document the customer signed must stay exactly as they saw it.

Columns of the quote_line_items table
ColumnTypeConstraintsReferencesDescription
iduuidPK
quote_iduuidFK, not nullquotes.id
product_iduuidFK, not nullproducts.id
descriptionvarchar(300)not nullCopied from the product, editable before sending
quantitynumeric(12,2)not null
list_price_centsbigintnot null
unit_price_centsbigintnot null
discount_pctnumeric(5,2)not null, default 0
total_centsbigintnot null
sort_ordersmallintnot null

activities

Calls, emails, meetings and tasks in one table, so a timeline is one query and one ordering.

Columns of the activities table
ColumnTypeConstraintsReferencesDescription
iduuidPK
kindactivity_kindnot null
subjectvarchar(300)not null
bodytextCall notes, meeting agenda, or the email body
owner_iduuidFK, not nullusers.idWho made the call or holds the task
directionactivity_directionCalls and emails only
statusactivity_statusnot null, default 'open'Logged calls and emails are created completed
due_attimestamptzTasks
starts_attimestamptzMeetings
ends_attimestamptz
completed_attimestamptz
created_attimestamptznot null, default `now()`

Indexes: (owner_id, status, due_at)

notes

Free-form notes on one record, using the same exactly-one typed foreign key pattern as activity_links.

Columns of the notes table
ColumnTypeConstraintsReferences
iduuidPK
author_iduuidFK, not nullusers.id
account_iduuidFKaccounts.id
contact_iduuidFKcontacts.id
lead_iduuidFKleads.id
opportunity_iduuidFKopportunities.id
bodytextnot null
is_pinnedbooleannot null, default false
created_attimestamptznot null, default `now()`
updated_attimestamptznot null, default `now()`

Enums (14)

user_role
admin, sales_manager, account_executive, sales_development_rep, marketing, read_only
campaign_kind
email, webinar, event, paid_ads, content, outbound
campaign_member_status
targeted, sent, responded, attended, unsubscribed
lead_source
web_form, referral, event, outbound, partner, paid_ads, list_import
lead_status
new, working, nurturing, qualified, disqualified, converted
account_type
prospect, customer, former_customer, partner, competitor
stage_outcome
open, won, lost
forecast_category
omitted, pipeline, best_case, commit, closed
contact_role
decision_maker, economic_buyer, champion, influencer, technical_evaluator, end_user, blocker
billing_frequency
one_time, monthly, annual
quote_status
draft, sent, accepted, rejected, expired, superseded
activity_kind
call, email, meeting, task
activity_direction
inbound, outbound
activity_status
open, completed, canceled

Relationships (59)

  • account_domains.account_id references accounts.id many to one
  • accounts.owner_id references users.id many to one
  • accounts.parent_account_id references accounts.id many to one
  • activities.owner_id references users.id many to one
  • activity_links.account_id references accounts.id many to one
  • activity_links.activity_id references activities.id many to one
  • activity_links.contact_id references contacts.id many to one
  • activity_links.lead_id references leads.id many to one
  • activity_links.opportunity_id references opportunities.id many to one
  • campaign_members.campaign_id references campaigns.id many to one
  • campaign_members.contact_id references contacts.id many to one
  • campaign_members.lead_id references leads.id many to one
  • campaigns.owner_id references users.id many to one
  • contacts.account_id references accounts.id many to one
  • contacts.owner_id references users.id many to one
  • lead_conversions.account_id references accounts.id many to one
  • lead_conversions.contact_id references contacts.id many to one
  • lead_conversions.converted_by references users.id many to one
  • lead_conversions.opportunity_id references opportunities.id many to one
  • leads.campaign_id references campaigns.id many to one
  • leads.id references lead_conversions.lead_id one to one
  • leads.owner_id references users.id many to one
  • notes.account_id references accounts.id many to one
  • notes.author_id references users.id many to one
  • notes.contact_id references contacts.id many to one
  • notes.lead_id references leads.id many to one
  • notes.opportunity_id references opportunities.id many to one
  • opportunities.account_id references accounts.id many to one
  • opportunities.owner_id references users.id many to one
  • opportunities.pipeline_id references pipelines.id many to one
  • opportunities.price_book_id references price_books.id many to one
  • opportunities.stage_id references pipeline_stages.id many to one
  • opportunity_contacts.contact_id references contacts.id many to one
  • opportunity_contacts.opportunity_id references opportunities.id many to one
  • opportunity_line_items.opportunity_id references opportunities.id many to one
  • opportunity_line_items.price_book_entry_id references price_book_entries.id many to one
  • opportunity_line_items.product_id references products.id many to one
  • opportunity_stage_history.changed_by references users.id many to one
  • opportunity_stage_history.from_stage_id references pipeline_stages.id many to one
  • opportunity_stage_history.opportunity_id references opportunities.id many to one
  • opportunity_stage_history.to_stage_id references pipeline_stages.id many to one
  • ownership_history.account_id references accounts.id many to one
  • ownership_history.changed_by references users.id many to one
  • ownership_history.contact_id references contacts.id many to one
  • ownership_history.from_user_id references users.id many to one
  • ownership_history.lead_id references leads.id many to one
  • ownership_history.opportunity_id references opportunities.id many to one
  • ownership_history.to_user_id references users.id many to one
  • pipeline_stages.pipeline_id references pipelines.id many to one
  • price_book_entries.price_book_id references price_books.id many to one
  • price_book_entries.product_id references products.id many to one
  • quote_line_items.product_id references products.id many to one
  • quote_line_items.quote_id references quotes.id many to one
  • quotes.created_by references users.id many to one
  • quotes.opportunity_id references opportunities.id many to one
  • teams.manager_id references users.id many to one
  • teams.parent_team_id references teams.id many to one
  • users.manager_id references users.id many to one
  • users.team_id references teams.id many to one

CRM database schema in DBML

The schema as it is written: DBML, the text format DB Planner draws its diagrams from. Copy it into any DBML tool, or open it in the diagram above.

crm.dbml dbml
// CRM
// Zones (header colors): users and ownership (gray), leads and campaigns (teal),
// accounts and contacts (blue), sales pipeline (amber), products and quotes (purple),
// activities and notes (green).

// ---------------------------------------------------------------------------
// USERS AND OWNERSHIP
// ---------------------------------------------------------------------------

Table teams [headercolor: #90a4ae] {
  id uuid [pk]
  name varchar(120) [not null, note: 'e.g. EMEA Mid-Market, Inside Sales']
  parent_team_id uuid [ref: > teams.id, note: 'Teams roll up into regions, so a forecast can be read at any level']
  manager_id uuid [ref: > users.id]
  created_at timestamptz [not null, default: `now()`]
  Note: 'Sales teams. The hierarchy is what forecast roll-ups and pipeline reviews are grouped by.'
}

Table users [headercolor: #90a4ae] {
  id uuid [pk]
  email varchar(254) [not null, unique]
  full_name varchar(200) [not null]
  role user_role [not null]
  team_id uuid [ref: > teams.id]
  manager_id uuid [ref: > users.id]
  timezone varchar(64) [not null, default: 'UTC']
  created_at timestamptz [not null, default: `now()`]
  deactivated_at timestamptz [note: 'Reps leave; their records are reassigned, never orphaned or deleted']
  Note: 'People who use the CRM. Every account, contact, lead and opportunity has an owner here.'
}

Table ownership_history [headercolor: #90a4ae] {
  id uuid [pk]
  account_id uuid [ref: > accounts.id]
  contact_id uuid [ref: > contacts.id]
  lead_id uuid [ref: > leads.id]
  opportunity_id uuid [ref: > opportunities.id]
  from_user_id uuid [ref: > users.id, note: 'Null for the first assignment']
  to_user_id uuid [not null, ref: > users.id]
  changed_by uuid [ref: > users.id, note: 'Null for assignment rules and round-robin routing']
  reason varchar(200) [note: 'e.g. territory realignment, rep left, round-robin']
  changed_at timestamptz [not null, default: `now()`]

  indexes {
    account_id
    contact_id
    lead_id
    opportunity_id
  }

  Note: '''Who owned which record, and when. Exactly one of the four record columns is set (CHECK num_nonnulls(...) = 1). Commission disputes, territory moves and "who was working this deal in Q2?" are all answered here, because the owner_id on the record only knows the present.'''
}

// ---------------------------------------------------------------------------
// LEADS AND CAMPAIGNS
// ---------------------------------------------------------------------------

Table campaigns [headercolor: #4cd0b0] {
  id uuid [pk]
  name varchar(200) [not null]
  kind campaign_kind [not null]
  owner_id uuid [not null, ref: > users.id]
  starts_on date
  ends_on date
  budget_cents bigint
  currency char(3) [not null]
  created_at timestamptz [not null, default: `now()`]
  Note: 'Marketing efforts that produce leads: a webinar, a trade show, a paid search push.'
}

Table campaign_members [headercolor: #4cd0b0] {
  id uuid [pk]
  campaign_id uuid [not null, ref: > campaigns.id]
  lead_id uuid [ref: > leads.id]
  contact_id uuid [ref: > contacts.id]
  status campaign_member_status [not null, default: 'targeted']
  first_responded_at timestamptz
  created_at timestamptz [not null, default: `now()`]

  indexes {
    (campaign_id, lead_id) [unique]
    (campaign_id, contact_id) [unique]
  }

  Note: 'Who a campaign reached. Exactly one of lead_id or contact_id is set, since campaigns target existing customers too.'
}

Table leads [headercolor: #4cd0b0] {
  id uuid [pk]
  owner_id uuid [ref: > users.id, note: 'Null while unassigned in the routing queue']
  first_name varchar(100)
  last_name varchar(100) [not null]
  email varchar(254)
  phone varchar(30)
  job_title varchar(150)
  company_name varchar(200) [note: 'Free text. A lead has a company NAME, not an account; the account is created or matched at conversion.']
  source lead_source [not null]
  campaign_id uuid [ref: > campaigns.id, note: 'First-touch campaign, kept for attribution']
  status lead_status [not null, default: 'new']
  score smallint [note: 'Fit and engagement score, 0 to 100']
  disqualified_reason varchar(200)
  created_at timestamptz [not null, default: `now()`]

  indexes {
    email
    (owner_id, status)
  }

  Note: '''Unqualified interest, kept apart from contacts. Leads are noisy (form fills, badge scans, list imports) and most never convert; mixing them into contacts pollutes every customer report and count.'''
}

Table lead_conversions [headercolor: #4cd0b0] {
  lead_id uuid [pk, ref: - leads.id]
  account_id uuid [not null, ref: > accounts.id]
  contact_id uuid [not null, ref: > contacts.id]
  opportunity_id uuid [ref: > opportunities.id, note: 'Null when the lead converted without a deal yet']
  created_account boolean [not null, note: 'False when the lead was matched to an existing account']
  created_contact boolean [not null]
  converted_by uuid [not null, ref: > users.id]
  converted_at timestamptz [not null, default: `now()`]
  Note: 'Where a qualified lead went. The lead row stays, read-only, so its source and campaign are credited with any revenue the opportunity later wins.'
}

// ---------------------------------------------------------------------------
// ACCOUNTS AND CONTACTS
// ---------------------------------------------------------------------------

Table accounts [headercolor: #4c8bf5] {
  id uuid [pk]
  name varchar(200) [not null]
  parent_account_id uuid [ref: > accounts.id, note: 'Subsidiary to parent, for account hierarchies and roll-ups']
  owner_id uuid [not null, ref: > users.id]
  type account_type [not null, default: 'prospect']
  industry varchar(100)
  employee_count integer
  annual_revenue_cents bigint
  website varchar(300)
  billing_country char(2) [note: 'ISO 3166-1 alpha-2. Territory rules key off it.']
  created_at timestamptz [not null, default: `now()`]
  updated_at timestamptz [not null, default: `now()`]
  deleted_at timestamptz

  indexes {
    owner_id
    name
  }

  Note: 'Companies you sell to, partner with or compete against.'
}

Table account_domains [headercolor: #4c8bf5] {
  domain varchar(253) [pk, note: 'Lowercase, e.g. example.com']
  account_id uuid [not null, ref: > accounts.id]
  is_primary boolean [not null, default: false]
  Note: 'Email domains an account owns. New leads, contacts and logged emails are matched to accounts by domain; free-mail domains are excluded in app code.'
}

Table contacts [headercolor: #4c8bf5] {
  id uuid [pk]
  account_id uuid [ref: > accounts.id, note: 'Null for an individual with no company']
  owner_id uuid [not null, ref: > users.id]
  first_name varchar(100)
  last_name varchar(100) [not null]
  email varchar(254)
  phone varchar(30)
  job_title varchar(150)
  department varchar(100)
  email_opted_out_at timestamptz [note: 'Consent is a timestamp, not a boolean, so you can prove when it was withdrawn']
  created_at timestamptz [not null, default: `now()`]
  updated_at timestamptz [not null, default: `now()`]
  deleted_at timestamptz

  indexes {
    account_id
    (`lower(email)`) [unique, note: 'Case-insensitive duplicate guard']
  }

  Note: 'Qualified people, usually at an account. Their role on a specific deal lives on opportunity_contacts.'
}

// ---------------------------------------------------------------------------
// SALES PIPELINE
// ---------------------------------------------------------------------------

Table pipelines [headercolor: #f5b74c] {
  id uuid [pk]
  name varchar(100) [not null, note: 'e.g. New business, Renewals, Partner deals']
  is_default boolean [not null, default: false]
  created_at timestamptz [not null, default: `now()`]
  Note: 'A sales process. New business and renewals rarely share the same stages.'
}

Table pipeline_stages [headercolor: #f5b74c] {
  id uuid [pk]
  pipeline_id uuid [not null, ref: > pipelines.id]
  name varchar(100) [not null, note: 'e.g. Discovery, Demo, Proposal, Negotiation, Closed won']
  position smallint [not null]
  probability_pct smallint [not null, note: 'Default win probability, 0 to 100, for weighted pipeline']
  forecast_category forecast_category [not null, note: 'Default bucket for deals entering this stage']
  outcome stage_outcome [not null, default: 'open', note: 'Whether reaching this stage closes the deal']

  indexes {
    (pipeline_id, position) [unique]
    (pipeline_id, name) [unique]
  }

  Note: 'Stages as DATA, not an enum, so sales ops can add, rename and reorder them per pipeline without a migration. Reports read outcome and forecast_category, never the stage name.'
}

Table opportunities [headercolor: #f5b74c] {
  id uuid [pk]
  account_id uuid [not null, ref: > accounts.id]
  name varchar(200) [not null, note: 'e.g. Example Corp, 250 seats, FY27']
  owner_id uuid [not null, ref: > users.id]
  pipeline_id uuid [not null, ref: > pipelines.id]
  stage_id uuid [not null, ref: > pipeline_stages.id]
  price_book_id uuid [ref: > price_books.id, note: 'Chosen when the first product is added; sets the currency']
  amount_cents bigint [not null, default: 0, note: 'Sum of line items, or entered by hand on a deal with no products yet']
  currency char(3) [not null]
  close_date date [not null, note: 'Expected close date while open, actual once closed']
  probability_pct smallint [not null]
  forecast_category forecast_category [not null, note: 'Starts from the stage default; the rep may override it']
  next_step varchar(300)
  lost_reason varchar(200)
  created_at timestamptz [not null, default: `now()`]
  closed_at timestamptz

  indexes {
    (owner_id, close_date) [note: 'My pipeline this quarter']
    stage_id
    account_id
  }

  Note: 'A deal: an amount, a close date and a stage. Only the current values live here; how they moved over time is in opportunity_stage_history.'
}

Table opportunity_stage_history [headercolor: #f5b74c] {
  id uuid [pk]
  opportunity_id uuid [not null, ref: > opportunities.id]
  from_stage_id uuid [ref: > pipeline_stages.id, note: 'Null on the first row, when the deal is created']
  to_stage_id uuid [not null, ref: > pipeline_stages.id]
  amount_cents bigint [not null]
  currency char(3) [not null]
  close_date date [not null]
  probability_pct smallint [not null]
  forecast_category forecast_category [not null]
  changed_by uuid [ref: > users.id]
  changed_at timestamptz [not null, default: `now()`]

  indexes {
    (opportunity_id, changed_at)
  }

  Note: '''Append-only. A row is written whenever the stage, amount, close date or forecast category changes, carrying the full forecast state after the change. "What did the Q3 commit look like on September 1?" is the latest row per opportunity at or before that instant. Stage conversion rates, deal velocity and slipped close dates all come from here; none of them can be rebuilt from the current row.'''
}

Table opportunity_contacts [headercolor: #f5b74c] {
  opportunity_id uuid [not null, ref: > opportunities.id]
  contact_id uuid [not null, ref: > contacts.id]
  role contact_role [not null]
  is_primary boolean [not null, default: false]

  indexes {
    (opportunity_id, contact_id) [pk]
  }

  Note: 'The buying committee. The same person can be the champion on one deal and a blocker on the next.'
}

// ---------------------------------------------------------------------------
// PRODUCTS AND QUOTES
// ---------------------------------------------------------------------------

Table products [headercolor: #b98cf0] {
  id uuid [pk]
  sku varchar(60) [not null, unique]
  name varchar(200) [not null]
  description text
  family varchar(100) [note: 'e.g. Platform, Add-ons, Services']
  billing billing_frequency [not null]
  is_active boolean [not null, default: true]
  created_at timestamptz [not null, default: `now()`]
  Note: 'What you sell. Holds no price: prices live in price books.'
}

Table price_books [headercolor: #b98cf0] {
  id uuid [pk]
  name varchar(100) [not null, note: 'e.g. Standard USD, Partner EUR, Education']
  currency char(3) [not null]
  is_standard boolean [not null, default: false, note: 'One standard book per currency']
  valid_from date
  valid_to date
  is_active boolean [not null, default: true]
  Note: 'Price lists. A standard list per currency plus regional, partner or negotiated books.'
}

Table price_book_entries [headercolor: #b98cf0] {
  id uuid [pk]
  price_book_id uuid [not null, ref: > price_books.id]
  product_id uuid [not null, ref: > products.id]
  list_price_cents bigint [not null]
  is_active boolean [not null, default: true]

  indexes {
    (price_book_id, product_id) [unique]
  }

  Note: 'The list price of one product in one price book.'
}

Table opportunity_line_items [headercolor: #b98cf0] {
  id uuid [pk]
  opportunity_id uuid [not null, ref: > opportunities.id]
  product_id uuid [not null, ref: > products.id]
  price_book_entry_id uuid [not null, ref: > price_book_entries.id]
  quantity numeric(12,2) [not null]
  list_price_cents bigint [not null, note: 'Snapshot of the entry price when the line was added']
  unit_price_cents bigint [not null, note: 'The price actually offered after negotiation']
  discount_pct numeric(5,2) [not null, default: 0]
  total_cents bigint [not null]
  sort_order smallint [not null]
  Note: 'Products on a deal, with prices snapshotted. A later price book change never moves a deal already in the forecast.'
}

Table quotes [headercolor: #b98cf0] {
  id uuid [pk]
  opportunity_id uuid [not null, ref: > opportunities.id]
  quote_number varchar(30) [not null, unique, note: 'e.g. Q-2026-00417']
  version smallint [not null, default: 1]
  status quote_status [not null, default: 'draft']
  currency char(3) [not null]
  subtotal_cents bigint [not null]
  discount_cents bigint [not null, default: 0]
  tax_cents bigint [not null, default: 0]
  total_cents bigint [not null]
  valid_until date [not null]
  created_by uuid [not null, ref: > users.id]
  created_at timestamptz [not null, default: `now()`]
  sent_at timestamptz
  accepted_at timestamptz

  indexes {
    (opportunity_id, version) [unique]
  }

  Note: 'A priced offer sent to the customer. Once sent it is never edited: a change is a new version, and the old one becomes superseded.'
}

Table quote_line_items [headercolor: #b98cf0] {
  id uuid [pk]
  quote_id uuid [not null, ref: > quotes.id]
  product_id uuid [not null, ref: > products.id]
  description varchar(300) [not null, note: 'Copied from the product, editable before sending']
  quantity numeric(12,2) [not null]
  list_price_cents bigint [not null]
  unit_price_cents bigint [not null]
  discount_pct numeric(5,2) [not null, default: 0]
  total_cents bigint [not null]
  sort_order smallint [not null]
  Note: 'Copied from the opportunity line items when the quote is generated, then frozen with it. The document the customer signed must stay exactly as they saw it.'
}

// ---------------------------------------------------------------------------
// ACTIVITIES AND NOTES
// ---------------------------------------------------------------------------

Table activities [headercolor: #8bc34a] {
  id uuid [pk]
  kind activity_kind [not null]
  subject varchar(300) [not null]
  body text [note: 'Call notes, meeting agenda, or the email body']
  owner_id uuid [not null, ref: > users.id, note: 'Who made the call or holds the task']
  direction activity_direction [note: 'Calls and emails only']
  status activity_status [not null, default: 'open', note: 'Logged calls and emails are created completed']
  due_at timestamptz [note: 'Tasks']
  starts_at timestamptz [note: 'Meetings']
  ends_at timestamptz
  completed_at timestamptz
  created_at timestamptz [not null, default: `now()`]

  indexes {
    (owner_id, status, due_at) [note: 'My open tasks']
  }

  Note: 'Calls, emails, meetings and tasks in one table, so a timeline is one query and one ordering.'
}

Table activity_links [headercolor: #8bc34a] {
  id uuid [pk]
  activity_id uuid [not null, ref: > activities.id]
  account_id uuid [ref: > accounts.id]
  contact_id uuid [ref: > contacts.id]
  lead_id uuid [ref: > leads.id]
  opportunity_id uuid [ref: > opportunities.id]

  indexes {
    activity_id
    account_id
    contact_id
    lead_id
    opportunity_id
  }

  Note: '''One activity, many records. A meeting with two contacts about one deal at one account is one activity and four links, so it shows on every timeline. Each link sets exactly one typed foreign key column (CHECK num_nonnulls(account_id, contact_id, lead_id, opportunity_id) = 1) rather than a record_type plus record_id pair, so the database enforces every link and none can dangle.'''
}

Table notes [headercolor: #8bc34a] {
  id uuid [pk]
  author_id uuid [not null, ref: > users.id]
  account_id uuid [ref: > accounts.id]
  contact_id uuid [ref: > contacts.id]
  lead_id uuid [ref: > leads.id]
  opportunity_id uuid [ref: > opportunities.id]
  body text [not null]
  is_pinned boolean [not null, default: false]
  created_at timestamptz [not null, default: `now()`]
  updated_at timestamptz [not null, default: `now()`]
  Note: 'Free-form notes on one record, using the same exactly-one typed foreign key pattern as activity_links.'
}

// ---------------------------------------------------------------------------
// ENUMS
// ---------------------------------------------------------------------------

Enum user_role {
  admin
  sales_manager
  account_executive
  sales_development_rep
  marketing
  read_only
}

Enum campaign_kind {
  email
  webinar
  event
  paid_ads
  content
  outbound
}

Enum campaign_member_status {
  targeted
  sent
  responded
  attended
  unsubscribed
}

Enum lead_source {
  web_form
  referral
  event
  outbound
  partner
  paid_ads
  list_import
}

Enum lead_status {
  new
  working
  nurturing
  qualified
  disqualified
  converted
}

Enum account_type {
  prospect
  customer
  former_customer
  partner
  competitor
}

Enum stage_outcome {
  open
  won
  lost
}

Enum forecast_category {
  omitted
  pipeline
  best_case
  commit
  closed
}

Enum contact_role {
  decision_maker
  economic_buyer
  champion
  influencer
  technical_evaluator
  end_user
  blocker
}

Enum billing_frequency {
  one_time
  monthly
  annual
}

Enum quote_status {
  draft
  sent
  accepted
  rejected
  expired
  superseded
}

Enum activity_kind {
  call
  email
  meeting
  task
}

Enum activity_direction {
  inbound
  outbound
}

Enum activity_status {
  open
  completed
  canceled
}

CRM database schema as SQL

The same schema as CREATE TABLE statements, exported by DB Planner. PostgreSQL is shown first; MySQL and SQL Server are below it.

PostgreSQL
postgresql.sql PostgreSQL
CREATE TYPE "user_role" AS ENUM (
  'admin',
  'sales_manager',
  'account_executive',
  'sales_development_rep',
  'marketing',
  'read_only'
);

CREATE TYPE "campaign_kind" AS ENUM (
  'email',
  'webinar',
  'event',
  'paid_ads',
  'content',
  'outbound'
);

CREATE TYPE "campaign_member_status" AS ENUM (
  'targeted',
  'sent',
  'responded',
  'attended',
  'unsubscribed'
);

CREATE TYPE "lead_source" AS ENUM (
  'web_form',
  'referral',
  'event',
  'outbound',
  'partner',
  'paid_ads',
  'list_import'
);

CREATE TYPE "lead_status" AS ENUM (
  'new',
  'working',
  'nurturing',
  'qualified',
  'disqualified',
  'converted'
);

CREATE TYPE "account_type" AS ENUM (
  'prospect',
  'customer',
  'former_customer',
  'partner',
  'competitor'
);

CREATE TYPE "stage_outcome" AS ENUM (
  'open',
  'won',
  'lost'
);

CREATE TYPE "forecast_category" AS ENUM (
  'omitted',
  'pipeline',
  'best_case',
  'commit',
  'closed'
);

CREATE TYPE "contact_role" AS ENUM (
  'decision_maker',
  'economic_buyer',
  'champion',
  'influencer',
  'technical_evaluator',
  'end_user',
  'blocker'
);

CREATE TYPE "billing_frequency" AS ENUM (
  'one_time',
  'monthly',
  'annual'
);

CREATE TYPE "quote_status" AS ENUM (
  'draft',
  'sent',
  'accepted',
  'rejected',
  'expired',
  'superseded'
);

CREATE TYPE "activity_kind" AS ENUM (
  'call',
  'email',
  'meeting',
  'task'
);

CREATE TYPE "activity_direction" AS ENUM (
  'inbound',
  'outbound'
);

CREATE TYPE "activity_status" AS ENUM (
  'open',
  'completed',
  'canceled'
);

CREATE TABLE "teams" (
  "id" uuid PRIMARY KEY,
  "name" varchar(120) NOT NULL,
  "parent_team_id" uuid,
  "manager_id" uuid,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "users" (
  "id" uuid PRIMARY KEY,
  "email" varchar(254) UNIQUE NOT NULL,
  "full_name" varchar(200) NOT NULL,
  "role" user_role NOT NULL,
  "team_id" uuid,
  "manager_id" uuid,
  "timezone" varchar(64) NOT NULL DEFAULT 'UTC',
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "deactivated_at" timestamptz
);

CREATE TABLE "ownership_history" (
  "id" uuid PRIMARY KEY,
  "account_id" uuid,
  "contact_id" uuid,
  "lead_id" uuid,
  "opportunity_id" uuid,
  "from_user_id" uuid,
  "to_user_id" uuid NOT NULL,
  "changed_by" uuid,
  "reason" varchar(200),
  "changed_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "campaigns" (
  "id" uuid PRIMARY KEY,
  "name" varchar(200) NOT NULL,
  "kind" campaign_kind NOT NULL,
  "owner_id" uuid NOT NULL,
  "starts_on" date,
  "ends_on" date,
  "budget_cents" bigint,
  "currency" char(3) NOT NULL,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "campaign_members" (
  "id" uuid PRIMARY KEY,
  "campaign_id" uuid NOT NULL,
  "lead_id" uuid,
  "contact_id" uuid,
  "status" campaign_member_status NOT NULL DEFAULT 'targeted',
  "first_responded_at" timestamptz,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "leads" (
  "id" uuid PRIMARY KEY,
  "owner_id" uuid,
  "first_name" varchar(100),
  "last_name" varchar(100) NOT NULL,
  "email" varchar(254),
  "phone" varchar(30),
  "job_title" varchar(150),
  "company_name" varchar(200),
  "source" lead_source NOT NULL,
  "campaign_id" uuid,
  "status" lead_status NOT NULL DEFAULT 'new',
  "score" smallint,
  "disqualified_reason" varchar(200),
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "lead_conversions" (
  "lead_id" uuid PRIMARY KEY,
  "account_id" uuid NOT NULL,
  "contact_id" uuid NOT NULL,
  "opportunity_id" uuid,
  "created_account" boolean NOT NULL,
  "created_contact" boolean NOT NULL,
  "converted_by" uuid NOT NULL,
  "converted_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "accounts" (
  "id" uuid PRIMARY KEY,
  "name" varchar(200) NOT NULL,
  "parent_account_id" uuid,
  "owner_id" uuid NOT NULL,
  "type" account_type NOT NULL DEFAULT 'prospect',
  "industry" varchar(100),
  "employee_count" integer,
  "annual_revenue_cents" bigint,
  "website" varchar(300),
  "billing_country" char(2),
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "updated_at" timestamptz NOT NULL DEFAULT (now()),
  "deleted_at" timestamptz
);

CREATE TABLE "account_domains" (
  "domain" varchar(253) PRIMARY KEY,
  "account_id" uuid NOT NULL,
  "is_primary" boolean NOT NULL DEFAULT false
);

CREATE TABLE "contacts" (
  "id" uuid PRIMARY KEY,
  "account_id" uuid,
  "owner_id" uuid NOT NULL,
  "first_name" varchar(100),
  "last_name" varchar(100) NOT NULL,
  "email" varchar(254),
  "phone" varchar(30),
  "job_title" varchar(150),
  "department" varchar(100),
  "email_opted_out_at" timestamptz,
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "updated_at" timestamptz NOT NULL DEFAULT (now()),
  "deleted_at" timestamptz
);

CREATE TABLE "pipelines" (
  "id" uuid PRIMARY KEY,
  "name" varchar(100) NOT NULL,
  "is_default" boolean NOT NULL DEFAULT false,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "pipeline_stages" (
  "id" uuid PRIMARY KEY,
  "pipeline_id" uuid NOT NULL,
  "name" varchar(100) NOT NULL,
  "position" smallint NOT NULL,
  "probability_pct" smallint NOT NULL,
  "forecast_category" forecast_category NOT NULL,
  "outcome" stage_outcome NOT NULL DEFAULT 'open'
);

CREATE TABLE "opportunities" (
  "id" uuid PRIMARY KEY,
  "account_id" uuid NOT NULL,
  "name" varchar(200) NOT NULL,
  "owner_id" uuid NOT NULL,
  "pipeline_id" uuid NOT NULL,
  "stage_id" uuid NOT NULL,
  "price_book_id" uuid,
  "amount_cents" bigint NOT NULL DEFAULT 0,
  "currency" char(3) NOT NULL,
  "close_date" date NOT NULL,
  "probability_pct" smallint NOT NULL,
  "forecast_category" forecast_category NOT NULL,
  "next_step" varchar(300),
  "lost_reason" varchar(200),
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "closed_at" timestamptz
);

CREATE TABLE "opportunity_stage_history" (
  "id" uuid PRIMARY KEY,
  "opportunity_id" uuid NOT NULL,
  "from_stage_id" uuid,
  "to_stage_id" uuid NOT NULL,
  "amount_cents" bigint NOT NULL,
  "currency" char(3) NOT NULL,
  "close_date" date NOT NULL,
  "probability_pct" smallint NOT NULL,
  "forecast_category" forecast_category NOT NULL,
  "changed_by" uuid,
  "changed_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "opportunity_contacts" (
  "opportunity_id" uuid NOT NULL,
  "contact_id" uuid NOT NULL,
  "role" contact_role NOT NULL,
  "is_primary" boolean NOT NULL DEFAULT false,
  PRIMARY KEY ("opportunity_id", "contact_id")
);

CREATE TABLE "products" (
  "id" uuid PRIMARY KEY,
  "sku" varchar(60) UNIQUE NOT NULL,
  "name" varchar(200) NOT NULL,
  "description" text,
  "family" varchar(100),
  "billing" billing_frequency NOT NULL,
  "is_active" boolean NOT NULL DEFAULT true,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "price_books" (
  "id" uuid PRIMARY KEY,
  "name" varchar(100) NOT NULL,
  "currency" char(3) NOT NULL,
  "is_standard" boolean NOT NULL DEFAULT false,
  "valid_from" date,
  "valid_to" date,
  "is_active" boolean NOT NULL DEFAULT true
);

CREATE TABLE "price_book_entries" (
  "id" uuid PRIMARY KEY,
  "price_book_id" uuid NOT NULL,
  "product_id" uuid NOT NULL,
  "list_price_cents" bigint NOT NULL,
  "is_active" boolean NOT NULL DEFAULT true
);

CREATE TABLE "opportunity_line_items" (
  "id" uuid PRIMARY KEY,
  "opportunity_id" uuid NOT NULL,
  "product_id" uuid NOT NULL,
  "price_book_entry_id" uuid NOT NULL,
  "quantity" numeric(12,2) NOT NULL,
  "list_price_cents" bigint NOT NULL,
  "unit_price_cents" bigint NOT NULL,
  "discount_pct" numeric(5,2) NOT NULL DEFAULT 0,
  "total_cents" bigint NOT NULL,
  "sort_order" smallint NOT NULL
);

CREATE TABLE "quotes" (
  "id" uuid PRIMARY KEY,
  "opportunity_id" uuid NOT NULL,
  "quote_number" varchar(30) UNIQUE NOT NULL,
  "version" smallint NOT NULL DEFAULT 1,
  "status" quote_status NOT NULL DEFAULT 'draft',
  "currency" char(3) NOT NULL,
  "subtotal_cents" bigint NOT NULL,
  "discount_cents" bigint NOT NULL DEFAULT 0,
  "tax_cents" bigint NOT NULL DEFAULT 0,
  "total_cents" bigint NOT NULL,
  "valid_until" date NOT NULL,
  "created_by" uuid NOT NULL,
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "sent_at" timestamptz,
  "accepted_at" timestamptz
);

CREATE TABLE "quote_line_items" (
  "id" uuid PRIMARY KEY,
  "quote_id" uuid NOT NULL,
  "product_id" uuid NOT NULL,
  "description" varchar(300) NOT NULL,
  "quantity" numeric(12,2) NOT NULL,
  "list_price_cents" bigint NOT NULL,
  "unit_price_cents" bigint NOT NULL,
  "discount_pct" numeric(5,2) NOT NULL DEFAULT 0,
  "total_cents" bigint NOT NULL,
  "sort_order" smallint NOT NULL
);

CREATE TABLE "activities" (
  "id" uuid PRIMARY KEY,
  "kind" activity_kind NOT NULL,
  "subject" varchar(300) NOT NULL,
  "body" text,
  "owner_id" uuid NOT NULL,
  "direction" activity_direction,
  "status" activity_status NOT NULL DEFAULT 'open',
  "due_at" timestamptz,
  "starts_at" timestamptz,
  "ends_at" timestamptz,
  "completed_at" timestamptz,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "activity_links" (
  "id" uuid PRIMARY KEY,
  "activity_id" uuid NOT NULL,
  "account_id" uuid,
  "contact_id" uuid,
  "lead_id" uuid,
  "opportunity_id" uuid
);

CREATE TABLE "notes" (
  "id" uuid PRIMARY KEY,
  "author_id" uuid NOT NULL,
  "account_id" uuid,
  "contact_id" uuid,
  "lead_id" uuid,
  "opportunity_id" uuid,
  "body" text NOT NULL,
  "is_pinned" boolean NOT NULL DEFAULT false,
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "updated_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE INDEX ON "ownership_history" ("account_id");

CREATE INDEX ON "ownership_history" ("contact_id");

CREATE INDEX ON "ownership_history" ("lead_id");

CREATE INDEX ON "ownership_history" ("opportunity_id");

CREATE UNIQUE INDEX ON "campaign_members" ("campaign_id", "lead_id");

CREATE UNIQUE INDEX ON "campaign_members" ("campaign_id", "contact_id");

CREATE INDEX ON "leads" ("email");

CREATE INDEX ON "leads" ("owner_id", "status");

CREATE INDEX ON "accounts" ("owner_id");

CREATE INDEX ON "accounts" ("name");

CREATE INDEX ON "contacts" ("account_id");

CREATE UNIQUE INDEX ON "contacts" ((lower(email)));

CREATE UNIQUE INDEX ON "pipeline_stages" ("pipeline_id", "position");

CREATE UNIQUE INDEX ON "pipeline_stages" ("pipeline_id", "name");

CREATE INDEX ON "opportunities" ("owner_id", "close_date");

CREATE INDEX ON "opportunities" ("stage_id");

CREATE INDEX ON "opportunities" ("account_id");

CREATE INDEX ON "opportunity_stage_history" ("opportunity_id", "changed_at");

CREATE UNIQUE INDEX ON "price_book_entries" ("price_book_id", "product_id");

CREATE UNIQUE INDEX ON "quotes" ("opportunity_id", "version");

CREATE INDEX ON "activities" ("owner_id", "status", "due_at");

CREATE INDEX ON "activity_links" ("activity_id");

CREATE INDEX ON "activity_links" ("account_id");

CREATE INDEX ON "activity_links" ("contact_id");

CREATE INDEX ON "activity_links" ("lead_id");

CREATE INDEX ON "activity_links" ("opportunity_id");

COMMENT ON TABLE "teams" IS 'Sales teams. The hierarchy is what forecast roll-ups and pipeline reviews are grouped by.';

COMMENT ON COLUMN "teams"."name" IS 'e.g. EMEA Mid-Market, Inside Sales';

COMMENT ON COLUMN "teams"."parent_team_id" IS 'Teams roll up into regions, so a forecast can be read at any level';

COMMENT ON TABLE "users" IS 'People who use the CRM. Every account, contact, lead and opportunity has an owner here.';

COMMENT ON COLUMN "users"."deactivated_at" IS 'Reps leave; their records are reassigned, never orphaned or deleted';

COMMENT ON TABLE "ownership_history" IS 'Who owned which record, and when. Exactly one of the four record columns is set (CHECK num_nonnulls(...) = 1). Commission disputes, territory moves and "who was working this deal in Q2?" are all answered here, because the owner_id on the record only knows the present.';

COMMENT ON COLUMN "ownership_history"."from_user_id" IS 'Null for the first assignment';

COMMENT ON COLUMN "ownership_history"."changed_by" IS 'Null for assignment rules and round-robin routing';

COMMENT ON COLUMN "ownership_history"."reason" IS 'e.g. territory realignment, rep left, round-robin';

COMMENT ON TABLE "campaigns" IS 'Marketing efforts that produce leads: a webinar, a trade show, a paid search push.';

COMMENT ON TABLE "campaign_members" IS 'Who a campaign reached. Exactly one of lead_id or contact_id is set, since campaigns target existing customers too.';

COMMENT ON TABLE "leads" IS 'Unqualified interest, kept apart from contacts. Leads are noisy (form fills, badge scans, list imports) and most never convert; mixing them into contacts pollutes every customer report and count.';

COMMENT ON COLUMN "leads"."owner_id" IS 'Null while unassigned in the routing queue';

COMMENT ON COLUMN "leads"."company_name" IS 'Free text. A lead has a company NAME, not an account; the account is created or matched at conversion.';

COMMENT ON COLUMN "leads"."campaign_id" IS 'First-touch campaign, kept for attribution';

COMMENT ON COLUMN "leads"."score" IS 'Fit and engagement score, 0 to 100';

COMMENT ON TABLE "lead_conversions" IS 'Where a qualified lead went. The lead row stays, read-only, so its source and campaign are credited with any revenue the opportunity later wins.';

COMMENT ON COLUMN "lead_conversions"."opportunity_id" IS 'Null when the lead converted without a deal yet';

COMMENT ON COLUMN "lead_conversions"."created_account" IS 'False when the lead was matched to an existing account';

COMMENT ON TABLE "accounts" IS 'Companies you sell to, partner with or compete against.';

COMMENT ON COLUMN "accounts"."parent_account_id" IS 'Subsidiary to parent, for account hierarchies and roll-ups';

COMMENT ON COLUMN "accounts"."billing_country" IS 'ISO 3166-1 alpha-2. Territory rules key off it.';

COMMENT ON TABLE "account_domains" IS 'Email domains an account owns. New leads, contacts and logged emails are matched to accounts by domain; free-mail domains are excluded in app code.';

COMMENT ON COLUMN "account_domains"."domain" IS 'Lowercase, e.g. example.com';

COMMENT ON TABLE "contacts" IS 'Qualified people, usually at an account. Their role on a specific deal lives on opportunity_contacts.';

COMMENT ON COLUMN "contacts"."account_id" IS 'Null for an individual with no company';

COMMENT ON COLUMN "contacts"."email_opted_out_at" IS 'Consent is a timestamp, not a boolean, so you can prove when it was withdrawn';

COMMENT ON TABLE "pipelines" IS 'A sales process. New business and renewals rarely share the same stages.';

COMMENT ON COLUMN "pipelines"."name" IS 'e.g. New business, Renewals, Partner deals';

COMMENT ON TABLE "pipeline_stages" IS 'Stages as DATA, not an enum, so sales ops can add, rename and reorder them per pipeline without a migration. Reports read outcome and forecast_category, never the stage name.';

COMMENT ON COLUMN "pipeline_stages"."name" IS 'e.g. Discovery, Demo, Proposal, Negotiation, Closed won';

COMMENT ON COLUMN "pipeline_stages"."probability_pct" IS 'Default win probability, 0 to 100, for weighted pipeline';

COMMENT ON COLUMN "pipeline_stages"."forecast_category" IS 'Default bucket for deals entering this stage';

COMMENT ON COLUMN "pipeline_stages"."outcome" IS 'Whether reaching this stage closes the deal';

COMMENT ON TABLE "opportunities" IS 'A deal: an amount, a close date and a stage. Only the current values live here; how they moved over time is in opportunity_stage_history.';

COMMENT ON COLUMN "opportunities"."name" IS 'e.g. Example Corp, 250 seats, FY27';

COMMENT ON COLUMN "opportunities"."price_book_id" IS 'Chosen when the first product is added; sets the currency';

COMMENT ON COLUMN "opportunities"."amount_cents" IS 'Sum of line items, or entered by hand on a deal with no products yet';

COMMENT ON COLUMN "opportunities"."close_date" IS 'Expected close date while open, actual once closed';

COMMENT ON COLUMN "opportunities"."forecast_category" IS 'Starts from the stage default; the rep may override it';

COMMENT ON TABLE "opportunity_stage_history" IS 'Append-only. A row is written whenever the stage, amount, close date or forecast category changes, carrying the full forecast state after the change. "What did the Q3 commit look like on September 1?" is the latest row per opportunity at or before that instant. Stage conversion rates, deal velocity and slipped close dates all come from here; none of them can be rebuilt from the current row.';

COMMENT ON COLUMN "opportunity_stage_history"."from_stage_id" IS 'Null on the first row, when the deal is created';

COMMENT ON TABLE "opportunity_contacts" IS 'The buying committee. The same person can be the champion on one deal and a blocker on the next.';

COMMENT ON TABLE "products" IS 'What you sell. Holds no price: prices live in price books.';

COMMENT ON COLUMN "products"."family" IS 'e.g. Platform, Add-ons, Services';

COMMENT ON TABLE "price_books" IS 'Price lists. A standard list per currency plus regional, partner or negotiated books.';

COMMENT ON COLUMN "price_books"."name" IS 'e.g. Standard USD, Partner EUR, Education';

COMMENT ON COLUMN "price_books"."is_standard" IS 'One standard book per currency';

COMMENT ON TABLE "price_book_entries" IS 'The list price of one product in one price book.';

COMMENT ON TABLE "opportunity_line_items" IS 'Products on a deal, with prices snapshotted. A later price book change never moves a deal already in the forecast.';

COMMENT ON COLUMN "opportunity_line_items"."list_price_cents" IS 'Snapshot of the entry price when the line was added';

COMMENT ON COLUMN "opportunity_line_items"."unit_price_cents" IS 'The price actually offered after negotiation';

COMMENT ON TABLE "quotes" IS 'A priced offer sent to the customer. Once sent it is never edited: a change is a new version, and the old one becomes superseded.';

COMMENT ON COLUMN "quotes"."quote_number" IS 'e.g. Q-2026-00417';

COMMENT ON TABLE "quote_line_items" IS 'Copied from the opportunity line items when the quote is generated, then frozen with it. The document the customer signed must stay exactly as they saw it.';

COMMENT ON COLUMN "quote_line_items"."description" IS 'Copied from the product, editable before sending';

COMMENT ON TABLE "activities" IS 'Calls, emails, meetings and tasks in one table, so a timeline is one query and one ordering.';

COMMENT ON COLUMN "activities"."body" IS 'Call notes, meeting agenda, or the email body';

COMMENT ON COLUMN "activities"."owner_id" IS 'Who made the call or holds the task';

COMMENT ON COLUMN "activities"."direction" IS 'Calls and emails only';

COMMENT ON COLUMN "activities"."status" IS 'Logged calls and emails are created completed';

COMMENT ON COLUMN "activities"."due_at" IS 'Tasks';

COMMENT ON COLUMN "activities"."starts_at" IS 'Meetings';

COMMENT ON TABLE "activity_links" IS 'One activity, many records. A meeting with two contacts about one deal at one account is one activity and four links, so it shows on every timeline. Each link sets exactly one typed foreign key column (CHECK num_nonnulls(account_id, contact_id, lead_id, opportunity_id) = 1) rather than a record_type plus record_id pair, so the database enforces every link and none can dangle.';

COMMENT ON TABLE "notes" IS 'Free-form notes on one record, using the same exactly-one typed foreign key pattern as activity_links.';

ALTER TABLE "teams" ADD FOREIGN KEY ("parent_team_id") REFERENCES "teams" ("id");

ALTER TABLE "teams" ADD FOREIGN KEY ("manager_id") REFERENCES "users" ("id");

ALTER TABLE "users" ADD FOREIGN KEY ("team_id") REFERENCES "teams" ("id");

ALTER TABLE "users" ADD FOREIGN KEY ("manager_id") REFERENCES "users" ("id");

ALTER TABLE "ownership_history" ADD FOREIGN KEY ("account_id") REFERENCES "accounts" ("id");

ALTER TABLE "ownership_history" ADD FOREIGN KEY ("contact_id") REFERENCES "contacts" ("id");

ALTER TABLE "ownership_history" ADD FOREIGN KEY ("lead_id") REFERENCES "leads" ("id");

ALTER TABLE "ownership_history" ADD FOREIGN KEY ("opportunity_id") REFERENCES "opportunities" ("id");

ALTER TABLE "ownership_history" ADD FOREIGN KEY ("from_user_id") REFERENCES "users" ("id");

ALTER TABLE "ownership_history" ADD FOREIGN KEY ("to_user_id") REFERENCES "users" ("id");

ALTER TABLE "ownership_history" ADD FOREIGN KEY ("changed_by") REFERENCES "users" ("id");

ALTER TABLE "campaigns" ADD FOREIGN KEY ("owner_id") REFERENCES "users" ("id");

ALTER TABLE "campaign_members" ADD FOREIGN KEY ("campaign_id") REFERENCES "campaigns" ("id");

ALTER TABLE "campaign_members" ADD FOREIGN KEY ("lead_id") REFERENCES "leads" ("id");

ALTER TABLE "campaign_members" ADD FOREIGN KEY ("contact_id") REFERENCES "contacts" ("id");

ALTER TABLE "leads" ADD FOREIGN KEY ("owner_id") REFERENCES "users" ("id");

ALTER TABLE "leads" ADD FOREIGN KEY ("campaign_id") REFERENCES "campaigns" ("id");

ALTER TABLE "lead_conversions" ADD FOREIGN KEY ("lead_id") REFERENCES "leads" ("id");

ALTER TABLE "lead_conversions" ADD FOREIGN KEY ("account_id") REFERENCES "accounts" ("id");

ALTER TABLE "lead_conversions" ADD FOREIGN KEY ("contact_id") REFERENCES "contacts" ("id");

ALTER TABLE "lead_conversions" ADD FOREIGN KEY ("opportunity_id") REFERENCES "opportunities" ("id");

ALTER TABLE "lead_conversions" ADD FOREIGN KEY ("converted_by") REFERENCES "users" ("id");

ALTER TABLE "accounts" ADD FOREIGN KEY ("parent_account_id") REFERENCES "accounts" ("id");

ALTER TABLE "accounts" ADD FOREIGN KEY ("owner_id") REFERENCES "users" ("id");

ALTER TABLE "account_domains" ADD FOREIGN KEY ("account_id") REFERENCES "accounts" ("id");

ALTER TABLE "contacts" ADD FOREIGN KEY ("account_id") REFERENCES "accounts" ("id");

ALTER TABLE "contacts" ADD FOREIGN KEY ("owner_id") REFERENCES "users" ("id");

ALTER TABLE "pipeline_stages" ADD FOREIGN KEY ("pipeline_id") REFERENCES "pipelines" ("id");

ALTER TABLE "opportunities" ADD FOREIGN KEY ("account_id") REFERENCES "accounts" ("id");

ALTER TABLE "opportunities" ADD FOREIGN KEY ("owner_id") REFERENCES "users" ("id");

ALTER TABLE "opportunities" ADD FOREIGN KEY ("pipeline_id") REFERENCES "pipelines" ("id");

ALTER TABLE "opportunities" ADD FOREIGN KEY ("stage_id") REFERENCES "pipeline_stages" ("id");

ALTER TABLE "opportunities" ADD FOREIGN KEY ("price_book_id") REFERENCES "price_books" ("id");

ALTER TABLE "opportunity_stage_history" ADD FOREIGN KEY ("opportunity_id") REFERENCES "opportunities" ("id");

ALTER TABLE "opportunity_stage_history" ADD FOREIGN KEY ("from_stage_id") REFERENCES "pipeline_stages" ("id");

ALTER TABLE "opportunity_stage_history" ADD FOREIGN KEY ("to_stage_id") REFERENCES "pipeline_stages" ("id");

ALTER TABLE "opportunity_stage_history" ADD FOREIGN KEY ("changed_by") REFERENCES "users" ("id");

ALTER TABLE "opportunity_contacts" ADD FOREIGN KEY ("opportunity_id") REFERENCES "opportunities" ("id");

ALTER TABLE "opportunity_contacts" ADD FOREIGN KEY ("contact_id") REFERENCES "contacts" ("id");

ALTER TABLE "price_book_entries" ADD FOREIGN KEY ("price_book_id") REFERENCES "price_books" ("id");

ALTER TABLE "price_book_entries" ADD FOREIGN KEY ("product_id") REFERENCES "products" ("id");

ALTER TABLE "opportunity_line_items" ADD FOREIGN KEY ("opportunity_id") REFERENCES "opportunities" ("id");

ALTER TABLE "opportunity_line_items" ADD FOREIGN KEY ("product_id") REFERENCES "products" ("id");

ALTER TABLE "opportunity_line_items" ADD FOREIGN KEY ("price_book_entry_id") REFERENCES "price_book_entries" ("id");

ALTER TABLE "quotes" ADD FOREIGN KEY ("opportunity_id") REFERENCES "opportunities" ("id");

ALTER TABLE "quotes" ADD FOREIGN KEY ("created_by") REFERENCES "users" ("id");

ALTER TABLE "quote_line_items" ADD FOREIGN KEY ("quote_id") REFERENCES "quotes" ("id");

ALTER TABLE "quote_line_items" ADD FOREIGN KEY ("product_id") REFERENCES "products" ("id");

ALTER TABLE "activities" ADD FOREIGN KEY ("owner_id") REFERENCES "users" ("id");

ALTER TABLE "activity_links" ADD FOREIGN KEY ("activity_id") REFERENCES "activities" ("id");

ALTER TABLE "activity_links" ADD FOREIGN KEY ("account_id") REFERENCES "accounts" ("id");

ALTER TABLE "activity_links" ADD FOREIGN KEY ("contact_id") REFERENCES "contacts" ("id");

ALTER TABLE "activity_links" ADD FOREIGN KEY ("lead_id") REFERENCES "leads" ("id");

ALTER TABLE "activity_links" ADD FOREIGN KEY ("opportunity_id") REFERENCES "opportunities" ("id");

ALTER TABLE "notes" ADD FOREIGN KEY ("author_id") REFERENCES "users" ("id");

ALTER TABLE "notes" ADD FOREIGN KEY ("account_id") REFERENCES "accounts" ("id");

ALTER TABLE "notes" ADD FOREIGN KEY ("contact_id") REFERENCES "contacts" ("id");

ALTER TABLE "notes" ADD FOREIGN KEY ("lead_id") REFERENCES "leads" ("id");

ALTER TABLE "notes" ADD FOREIGN KEY ("opportunity_id") REFERENCES "opportunities" ("id");
MySQL
mysql.sql MySQL
CREATE TABLE `teams` (
  `id` uuid PRIMARY KEY,
  `name` varchar(120) NOT NULL COMMENT 'e.g. EMEA Mid-Market, Inside Sales',
  `parent_team_id` uuid COMMENT 'Teams roll up into regions, so a forecast can be read at any level',
  `manager_id` uuid,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `users` (
  `id` uuid PRIMARY KEY,
  `email` varchar(254) UNIQUE NOT NULL,
  `full_name` varchar(200) NOT NULL,
  `role` ENUM ('admin', 'sales_manager', 'account_executive', 'sales_development_rep', 'marketing', 'read_only') NOT NULL,
  `team_id` uuid,
  `manager_id` uuid,
  `timezone` varchar(64) NOT NULL DEFAULT 'UTC',
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `deactivated_at` timestamptz COMMENT 'Reps leave; their records are reassigned, never orphaned or deleted'
);

CREATE TABLE `ownership_history` (
  `id` uuid PRIMARY KEY,
  `account_id` uuid,
  `contact_id` uuid,
  `lead_id` uuid,
  `opportunity_id` uuid,
  `from_user_id` uuid COMMENT 'Null for the first assignment',
  `to_user_id` uuid NOT NULL,
  `changed_by` uuid COMMENT 'Null for assignment rules and round-robin routing',
  `reason` varchar(200) COMMENT 'e.g. territory realignment, rep left, round-robin',
  `changed_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `campaigns` (
  `id` uuid PRIMARY KEY,
  `name` varchar(200) NOT NULL,
  `kind` ENUM ('email', 'webinar', 'event', 'paid_ads', 'content', 'outbound') NOT NULL,
  `owner_id` uuid NOT NULL,
  `starts_on` date,
  `ends_on` date,
  `budget_cents` bigint,
  `currency` char(3) NOT NULL,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `campaign_members` (
  `id` uuid PRIMARY KEY,
  `campaign_id` uuid NOT NULL,
  `lead_id` uuid,
  `contact_id` uuid,
  `status` ENUM ('targeted', 'sent', 'responded', 'attended', 'unsubscribed') NOT NULL DEFAULT 'targeted',
  `first_responded_at` timestamptz,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `leads` (
  `id` uuid PRIMARY KEY,
  `owner_id` uuid COMMENT 'Null while unassigned in the routing queue',
  `first_name` varchar(100),
  `last_name` varchar(100) NOT NULL,
  `email` varchar(254),
  `phone` varchar(30),
  `job_title` varchar(150),
  `company_name` varchar(200) COMMENT 'Free text. A lead has a company NAME, not an account; the account is created or matched at conversion.',
  `source` ENUM ('web_form', 'referral', 'event', 'outbound', 'partner', 'paid_ads', 'list_import') NOT NULL,
  `campaign_id` uuid COMMENT 'First-touch campaign, kept for attribution',
  `status` ENUM ('new', 'working', 'nurturing', 'qualified', 'disqualified', 'converted') NOT NULL DEFAULT 'new',
  `score` smallint COMMENT 'Fit and engagement score, 0 to 100',
  `disqualified_reason` varchar(200),
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `lead_conversions` (
  `lead_id` uuid PRIMARY KEY,
  `account_id` uuid NOT NULL,
  `contact_id` uuid NOT NULL,
  `opportunity_id` uuid COMMENT 'Null when the lead converted without a deal yet',
  `created_account` boolean NOT NULL COMMENT 'False when the lead was matched to an existing account',
  `created_contact` boolean NOT NULL,
  `converted_by` uuid NOT NULL,
  `converted_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `accounts` (
  `id` uuid PRIMARY KEY,
  `name` varchar(200) NOT NULL,
  `parent_account_id` uuid COMMENT 'Subsidiary to parent, for account hierarchies and roll-ups',
  `owner_id` uuid NOT NULL,
  `type` ENUM ('prospect', 'customer', 'former_customer', 'partner', 'competitor') NOT NULL DEFAULT 'prospect',
  `industry` varchar(100),
  `employee_count` integer,
  `annual_revenue_cents` bigint,
  `website` varchar(300),
  `billing_country` char(2) COMMENT 'ISO 3166-1 alpha-2. Territory rules key off it.',
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `updated_at` timestamptz NOT NULL DEFAULT (now()),
  `deleted_at` timestamptz
);

CREATE TABLE `account_domains` (
  `domain` varchar(253) PRIMARY KEY COMMENT 'Lowercase, e.g. example.com',
  `account_id` uuid NOT NULL,
  `is_primary` boolean NOT NULL DEFAULT false
);

CREATE TABLE `contacts` (
  `id` uuid PRIMARY KEY,
  `account_id` uuid COMMENT 'Null for an individual with no company',
  `owner_id` uuid NOT NULL,
  `first_name` varchar(100),
  `last_name` varchar(100) NOT NULL,
  `email` varchar(254),
  `phone` varchar(30),
  `job_title` varchar(150),
  `department` varchar(100),
  `email_opted_out_at` timestamptz COMMENT 'Consent is a timestamp, not a boolean, so you can prove when it was withdrawn',
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `updated_at` timestamptz NOT NULL DEFAULT (now()),
  `deleted_at` timestamptz
);

CREATE TABLE `pipelines` (
  `id` uuid PRIMARY KEY,
  `name` varchar(100) NOT NULL COMMENT 'e.g. New business, Renewals, Partner deals',
  `is_default` boolean NOT NULL DEFAULT false,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `pipeline_stages` (
  `id` uuid PRIMARY KEY,
  `pipeline_id` uuid NOT NULL,
  `name` varchar(100) NOT NULL COMMENT 'e.g. Discovery, Demo, Proposal, Negotiation, Closed won',
  `position` smallint NOT NULL,
  `probability_pct` smallint NOT NULL COMMENT 'Default win probability, 0 to 100, for weighted pipeline',
  `forecast_category` ENUM ('omitted', 'pipeline', 'best_case', 'commit', 'closed') NOT NULL COMMENT 'Default bucket for deals entering this stage',
  `outcome` ENUM ('open', 'won', 'lost') NOT NULL DEFAULT 'open' COMMENT 'Whether reaching this stage closes the deal'
);

CREATE TABLE `opportunities` (
  `id` uuid PRIMARY KEY,
  `account_id` uuid NOT NULL,
  `name` varchar(200) NOT NULL COMMENT 'e.g. Example Corp, 250 seats, FY27',
  `owner_id` uuid NOT NULL,
  `pipeline_id` uuid NOT NULL,
  `stage_id` uuid NOT NULL,
  `price_book_id` uuid COMMENT 'Chosen when the first product is added; sets the currency',
  `amount_cents` bigint NOT NULL DEFAULT 0 COMMENT 'Sum of line items, or entered by hand on a deal with no products yet',
  `currency` char(3) NOT NULL,
  `close_date` date NOT NULL COMMENT 'Expected close date while open, actual once closed',
  `probability_pct` smallint NOT NULL,
  `forecast_category` ENUM ('omitted', 'pipeline', 'best_case', 'commit', 'closed') NOT NULL COMMENT 'Starts from the stage default; the rep may override it',
  `next_step` varchar(300),
  `lost_reason` varchar(200),
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `closed_at` timestamptz
);

CREATE TABLE `opportunity_stage_history` (
  `id` uuid PRIMARY KEY,
  `opportunity_id` uuid NOT NULL,
  `from_stage_id` uuid COMMENT 'Null on the first row, when the deal is created',
  `to_stage_id` uuid NOT NULL,
  `amount_cents` bigint NOT NULL,
  `currency` char(3) NOT NULL,
  `close_date` date NOT NULL,
  `probability_pct` smallint NOT NULL,
  `forecast_category` ENUM ('omitted', 'pipeline', 'best_case', 'commit', 'closed') NOT NULL,
  `changed_by` uuid,
  `changed_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `opportunity_contacts` (
  `opportunity_id` uuid NOT NULL,
  `contact_id` uuid NOT NULL,
  `role` ENUM ('decision_maker', 'economic_buyer', 'champion', 'influencer', 'technical_evaluator', 'end_user', 'blocker') NOT NULL,
  `is_primary` boolean NOT NULL DEFAULT false,
  PRIMARY KEY (`opportunity_id`, `contact_id`)
);

CREATE TABLE `products` (
  `id` uuid PRIMARY KEY,
  `sku` varchar(60) UNIQUE NOT NULL,
  `name` varchar(200) NOT NULL,
  `description` text,
  `family` varchar(100) COMMENT 'e.g. Platform, Add-ons, Services',
  `billing` ENUM ('one_time', 'monthly', 'annual') NOT NULL,
  `is_active` boolean NOT NULL DEFAULT true,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `price_books` (
  `id` uuid PRIMARY KEY,
  `name` varchar(100) NOT NULL COMMENT 'e.g. Standard USD, Partner EUR, Education',
  `currency` char(3) NOT NULL,
  `is_standard` boolean NOT NULL DEFAULT false COMMENT 'One standard book per currency',
  `valid_from` date,
  `valid_to` date,
  `is_active` boolean NOT NULL DEFAULT true
);

CREATE TABLE `price_book_entries` (
  `id` uuid PRIMARY KEY,
  `price_book_id` uuid NOT NULL,
  `product_id` uuid NOT NULL,
  `list_price_cents` bigint NOT NULL,
  `is_active` boolean NOT NULL DEFAULT true
);

CREATE TABLE `opportunity_line_items` (
  `id` uuid PRIMARY KEY,
  `opportunity_id` uuid NOT NULL,
  `product_id` uuid NOT NULL,
  `price_book_entry_id` uuid NOT NULL,
  `quantity` numeric(12,2) NOT NULL,
  `list_price_cents` bigint NOT NULL COMMENT 'Snapshot of the entry price when the line was added',
  `unit_price_cents` bigint NOT NULL COMMENT 'The price actually offered after negotiation',
  `discount_pct` numeric(5,2) NOT NULL DEFAULT 0,
  `total_cents` bigint NOT NULL,
  `sort_order` smallint NOT NULL
);

CREATE TABLE `quotes` (
  `id` uuid PRIMARY KEY,
  `opportunity_id` uuid NOT NULL,
  `quote_number` varchar(30) UNIQUE NOT NULL COMMENT 'e.g. Q-2026-00417',
  `version` smallint NOT NULL DEFAULT 1,
  `status` ENUM ('draft', 'sent', 'accepted', 'rejected', 'expired', 'superseded') NOT NULL DEFAULT 'draft',
  `currency` char(3) NOT NULL,
  `subtotal_cents` bigint NOT NULL,
  `discount_cents` bigint NOT NULL DEFAULT 0,
  `tax_cents` bigint NOT NULL DEFAULT 0,
  `total_cents` bigint NOT NULL,
  `valid_until` date NOT NULL,
  `created_by` uuid NOT NULL,
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `sent_at` timestamptz,
  `accepted_at` timestamptz
);

CREATE TABLE `quote_line_items` (
  `id` uuid PRIMARY KEY,
  `quote_id` uuid NOT NULL,
  `product_id` uuid NOT NULL,
  `description` varchar(300) NOT NULL COMMENT 'Copied from the product, editable before sending',
  `quantity` numeric(12,2) NOT NULL,
  `list_price_cents` bigint NOT NULL,
  `unit_price_cents` bigint NOT NULL,
  `discount_pct` numeric(5,2) NOT NULL DEFAULT 0,
  `total_cents` bigint NOT NULL,
  `sort_order` smallint NOT NULL
);

CREATE TABLE `activities` (
  `id` uuid PRIMARY KEY,
  `kind` ENUM ('call', 'email', 'meeting', 'task') NOT NULL,
  `subject` varchar(300) NOT NULL,
  `body` text COMMENT 'Call notes, meeting agenda, or the email body',
  `owner_id` uuid NOT NULL COMMENT 'Who made the call or holds the task',
  `direction` ENUM ('inbound', 'outbound') COMMENT 'Calls and emails only',
  `status` ENUM ('open', 'completed', 'canceled') NOT NULL DEFAULT 'open' COMMENT 'Logged calls and emails are created completed',
  `due_at` timestamptz COMMENT 'Tasks',
  `starts_at` timestamptz COMMENT 'Meetings',
  `ends_at` timestamptz,
  `completed_at` timestamptz,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `activity_links` (
  `id` uuid PRIMARY KEY,
  `activity_id` uuid NOT NULL,
  `account_id` uuid,
  `contact_id` uuid,
  `lead_id` uuid,
  `opportunity_id` uuid
);

CREATE TABLE `notes` (
  `id` uuid PRIMARY KEY,
  `author_id` uuid NOT NULL,
  `account_id` uuid,
  `contact_id` uuid,
  `lead_id` uuid,
  `opportunity_id` uuid,
  `body` text NOT NULL,
  `is_pinned` boolean NOT NULL DEFAULT false,
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `updated_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE INDEX `ownership_history_index_0` ON `ownership_history` (`account_id`);

CREATE INDEX `ownership_history_index_1` ON `ownership_history` (`contact_id`);

CREATE INDEX `ownership_history_index_2` ON `ownership_history` (`lead_id`);

CREATE INDEX `ownership_history_index_3` ON `ownership_history` (`opportunity_id`);

CREATE UNIQUE INDEX `campaign_members_index_4` ON `campaign_members` (`campaign_id`, `lead_id`);

CREATE UNIQUE INDEX `campaign_members_index_5` ON `campaign_members` (`campaign_id`, `contact_id`);

CREATE INDEX `leads_index_6` ON `leads` (`email`);

CREATE INDEX `leads_index_7` ON `leads` (`owner_id`, `status`);

CREATE INDEX `accounts_index_8` ON `accounts` (`owner_id`);

CREATE INDEX `accounts_index_9` ON `accounts` (`name`);

CREATE INDEX `contacts_index_10` ON `contacts` (`account_id`);

CREATE UNIQUE INDEX `contacts_index_11` ON `contacts` ((lower(email)));

CREATE UNIQUE INDEX `pipeline_stages_index_12` ON `pipeline_stages` (`pipeline_id`, `position`);

CREATE UNIQUE INDEX `pipeline_stages_index_13` ON `pipeline_stages` (`pipeline_id`, `name`);

CREATE INDEX `opportunities_index_14` ON `opportunities` (`owner_id`, `close_date`);

CREATE INDEX `opportunities_index_15` ON `opportunities` (`stage_id`);

CREATE INDEX `opportunities_index_16` ON `opportunities` (`account_id`);

CREATE INDEX `opportunity_stage_history_index_17` ON `opportunity_stage_history` (`opportunity_id`, `changed_at`);

CREATE UNIQUE INDEX `price_book_entries_index_18` ON `price_book_entries` (`price_book_id`, `product_id`);

CREATE UNIQUE INDEX `quotes_index_19` ON `quotes` (`opportunity_id`, `version`);

CREATE INDEX `activities_index_20` ON `activities` (`owner_id`, `status`, `due_at`);

CREATE INDEX `activity_links_index_21` ON `activity_links` (`activity_id`);

CREATE INDEX `activity_links_index_22` ON `activity_links` (`account_id`);

CREATE INDEX `activity_links_index_23` ON `activity_links` (`contact_id`);

CREATE INDEX `activity_links_index_24` ON `activity_links` (`lead_id`);

CREATE INDEX `activity_links_index_25` ON `activity_links` (`opportunity_id`);

ALTER TABLE `teams` COMMENT = 'Sales teams. The hierarchy is what forecast roll-ups and pipeline reviews are grouped by.';

ALTER TABLE `users` COMMENT = 'People who use the CRM. Every account, contact, lead and opportunity has an owner here.';

ALTER TABLE `ownership_history` COMMENT = 'Who owned which record, and when. Exactly one of the four record columns is set (CHECK num_nonnulls(...) = 1). Commission disputes, territory moves and "who was working this deal in Q2?" are all answered here, because the owner_id on the record only knows the present.';

ALTER TABLE `campaigns` COMMENT = 'Marketing efforts that produce leads: a webinar, a trade show, a paid search push.';

ALTER TABLE `campaign_members` COMMENT = 'Who a campaign reached. Exactly one of lead_id or contact_id is set, since campaigns target existing customers too.';

ALTER TABLE `leads` COMMENT = 'Unqualified interest, kept apart from contacts. Leads are noisy (form fills, badge scans, list imports) and most never convert; mixing them into contacts pollutes every customer report and count.';

ALTER TABLE `lead_conversions` COMMENT = 'Where a qualified lead went. The lead row stays, read-only, so its source and campaign are credited with any revenue the opportunity later wins.';

ALTER TABLE `accounts` COMMENT = 'Companies you sell to, partner with or compete against.';

ALTER TABLE `account_domains` COMMENT = 'Email domains an account owns. New leads, contacts and logged emails are matched to accounts by domain; free-mail domains are excluded in app code.';

ALTER TABLE `contacts` COMMENT = 'Qualified people, usually at an account. Their role on a specific deal lives on opportunity_contacts.';

ALTER TABLE `pipelines` COMMENT = 'A sales process. New business and renewals rarely share the same stages.';

ALTER TABLE `pipeline_stages` COMMENT = 'Stages as DATA, not an enum, so sales ops can add, rename and reorder them per pipeline without a migration. Reports read outcome and forecast_category, never the stage name.';

ALTER TABLE `opportunities` COMMENT = 'A deal: an amount, a close date and a stage. Only the current values live here; how they moved over time is in opportunity_stage_history.';

ALTER TABLE `opportunity_stage_history` COMMENT = 'Append-only. A row is written whenever the stage, amount, close date or forecast category changes, carrying the full forecast state after the change. "What did the Q3 commit look like on September 1?" is the latest row per opportunity at or before that instant. Stage conversion rates, deal velocity and slipped close dates all come from here; none of them can be rebuilt from the current row.';

ALTER TABLE `opportunity_contacts` COMMENT = 'The buying committee. The same person can be the champion on one deal and a blocker on the next.';

ALTER TABLE `products` COMMENT = 'What you sell. Holds no price: prices live in price books.';

ALTER TABLE `price_books` COMMENT = 'Price lists. A standard list per currency plus regional, partner or negotiated books.';

ALTER TABLE `price_book_entries` COMMENT = 'The list price of one product in one price book.';

ALTER TABLE `opportunity_line_items` COMMENT = 'Products on a deal, with prices snapshotted. A later price book change never moves a deal already in the forecast.';

ALTER TABLE `quotes` COMMENT = 'A priced offer sent to the customer. Once sent it is never edited: a change is a new version, and the old one becomes superseded.';

ALTER TABLE `quote_line_items` COMMENT = 'Copied from the opportunity line items when the quote is generated, then frozen with it. The document the customer signed must stay exactly as they saw it.';

ALTER TABLE `activities` COMMENT = 'Calls, emails, meetings and tasks in one table, so a timeline is one query and one ordering.';

ALTER TABLE `activity_links` COMMENT = 'One activity, many records. A meeting with two contacts about one deal at one account is one activity and four links, so it shows on every timeline. Each link sets exactly one typed foreign key column (CHECK num_nonnulls(account_id, contact_id, lead_id, opportunity_id) = 1) rather than a record_type plus record_id pair, so the database enforces every link and none can dangle.';

ALTER TABLE `notes` COMMENT = 'Free-form notes on one record, using the same exactly-one typed foreign key pattern as activity_links.';

ALTER TABLE `teams` ADD FOREIGN KEY (`parent_team_id`) REFERENCES `teams` (`id`);

ALTER TABLE `teams` ADD FOREIGN KEY (`manager_id`) REFERENCES `users` (`id`);

ALTER TABLE `users` ADD FOREIGN KEY (`team_id`) REFERENCES `teams` (`id`);

ALTER TABLE `users` ADD FOREIGN KEY (`manager_id`) REFERENCES `users` (`id`);

ALTER TABLE `ownership_history` ADD FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`);

ALTER TABLE `ownership_history` ADD FOREIGN KEY (`contact_id`) REFERENCES `contacts` (`id`);

ALTER TABLE `ownership_history` ADD FOREIGN KEY (`lead_id`) REFERENCES `leads` (`id`);

ALTER TABLE `ownership_history` ADD FOREIGN KEY (`opportunity_id`) REFERENCES `opportunities` (`id`);

ALTER TABLE `ownership_history` ADD FOREIGN KEY (`from_user_id`) REFERENCES `users` (`id`);

ALTER TABLE `ownership_history` ADD FOREIGN KEY (`to_user_id`) REFERENCES `users` (`id`);

ALTER TABLE `ownership_history` ADD FOREIGN KEY (`changed_by`) REFERENCES `users` (`id`);

ALTER TABLE `campaigns` ADD FOREIGN KEY (`owner_id`) REFERENCES `users` (`id`);

ALTER TABLE `campaign_members` ADD FOREIGN KEY (`campaign_id`) REFERENCES `campaigns` (`id`);

ALTER TABLE `campaign_members` ADD FOREIGN KEY (`lead_id`) REFERENCES `leads` (`id`);

ALTER TABLE `campaign_members` ADD FOREIGN KEY (`contact_id`) REFERENCES `contacts` (`id`);

ALTER TABLE `leads` ADD FOREIGN KEY (`owner_id`) REFERENCES `users` (`id`);

ALTER TABLE `leads` ADD FOREIGN KEY (`campaign_id`) REFERENCES `campaigns` (`id`);

ALTER TABLE `lead_conversions` ADD FOREIGN KEY (`lead_id`) REFERENCES `leads` (`id`);

ALTER TABLE `lead_conversions` ADD FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`);

ALTER TABLE `lead_conversions` ADD FOREIGN KEY (`contact_id`) REFERENCES `contacts` (`id`);

ALTER TABLE `lead_conversions` ADD FOREIGN KEY (`opportunity_id`) REFERENCES `opportunities` (`id`);

ALTER TABLE `lead_conversions` ADD FOREIGN KEY (`converted_by`) REFERENCES `users` (`id`);

ALTER TABLE `accounts` ADD FOREIGN KEY (`parent_account_id`) REFERENCES `accounts` (`id`);

ALTER TABLE `accounts` ADD FOREIGN KEY (`owner_id`) REFERENCES `users` (`id`);

ALTER TABLE `account_domains` ADD FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`);

ALTER TABLE `contacts` ADD FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`);

ALTER TABLE `contacts` ADD FOREIGN KEY (`owner_id`) REFERENCES `users` (`id`);

ALTER TABLE `pipeline_stages` ADD FOREIGN KEY (`pipeline_id`) REFERENCES `pipelines` (`id`);

ALTER TABLE `opportunities` ADD FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`);

ALTER TABLE `opportunities` ADD FOREIGN KEY (`owner_id`) REFERENCES `users` (`id`);

ALTER TABLE `opportunities` ADD FOREIGN KEY (`pipeline_id`) REFERENCES `pipelines` (`id`);

ALTER TABLE `opportunities` ADD FOREIGN KEY (`stage_id`) REFERENCES `pipeline_stages` (`id`);

ALTER TABLE `opportunities` ADD FOREIGN KEY (`price_book_id`) REFERENCES `price_books` (`id`);

ALTER TABLE `opportunity_stage_history` ADD FOREIGN KEY (`opportunity_id`) REFERENCES `opportunities` (`id`);

ALTER TABLE `opportunity_stage_history` ADD FOREIGN KEY (`from_stage_id`) REFERENCES `pipeline_stages` (`id`);

ALTER TABLE `opportunity_stage_history` ADD FOREIGN KEY (`to_stage_id`) REFERENCES `pipeline_stages` (`id`);

ALTER TABLE `opportunity_stage_history` ADD FOREIGN KEY (`changed_by`) REFERENCES `users` (`id`);

ALTER TABLE `opportunity_contacts` ADD FOREIGN KEY (`opportunity_id`) REFERENCES `opportunities` (`id`);

ALTER TABLE `opportunity_contacts` ADD FOREIGN KEY (`contact_id`) REFERENCES `contacts` (`id`);

ALTER TABLE `price_book_entries` ADD FOREIGN KEY (`price_book_id`) REFERENCES `price_books` (`id`);

ALTER TABLE `price_book_entries` ADD FOREIGN KEY (`product_id`) REFERENCES `products` (`id`);

ALTER TABLE `opportunity_line_items` ADD FOREIGN KEY (`opportunity_id`) REFERENCES `opportunities` (`id`);

ALTER TABLE `opportunity_line_items` ADD FOREIGN KEY (`product_id`) REFERENCES `products` (`id`);

ALTER TABLE `opportunity_line_items` ADD FOREIGN KEY (`price_book_entry_id`) REFERENCES `price_book_entries` (`id`);

ALTER TABLE `quotes` ADD FOREIGN KEY (`opportunity_id`) REFERENCES `opportunities` (`id`);

ALTER TABLE `quotes` ADD FOREIGN KEY (`created_by`) REFERENCES `users` (`id`);

ALTER TABLE `quote_line_items` ADD FOREIGN KEY (`quote_id`) REFERENCES `quotes` (`id`);

ALTER TABLE `quote_line_items` ADD FOREIGN KEY (`product_id`) REFERENCES `products` (`id`);

ALTER TABLE `activities` ADD FOREIGN KEY (`owner_id`) REFERENCES `users` (`id`);

ALTER TABLE `activity_links` ADD FOREIGN KEY (`activity_id`) REFERENCES `activities` (`id`);

ALTER TABLE `activity_links` ADD FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`);

ALTER TABLE `activity_links` ADD FOREIGN KEY (`contact_id`) REFERENCES `contacts` (`id`);

ALTER TABLE `activity_links` ADD FOREIGN KEY (`lead_id`) REFERENCES `leads` (`id`);

ALTER TABLE `activity_links` ADD FOREIGN KEY (`opportunity_id`) REFERENCES `opportunities` (`id`);

ALTER TABLE `notes` ADD FOREIGN KEY (`author_id`) REFERENCES `users` (`id`);

ALTER TABLE `notes` ADD FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`);

ALTER TABLE `notes` ADD FOREIGN KEY (`contact_id`) REFERENCES `contacts` (`id`);

ALTER TABLE `notes` ADD FOREIGN KEY (`lead_id`) REFERENCES `leads` (`id`);

ALTER TABLE `notes` ADD FOREIGN KEY (`opportunity_id`) REFERENCES `opportunities` (`id`);
SQL Server
sql-server.sql SQL Server
CREATE TABLE [teams] (
  [id] uuid PRIMARY KEY,
  [name] varchar(120) NOT NULL,
  [parent_team_id] uuid,
  [manager_id] uuid,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [users] (
  [id] uuid PRIMARY KEY,
  [email] varchar(254) UNIQUE NOT NULL,
  [full_name] varchar(200) NOT NULL,
  [role] nvarchar(255) NOT NULL CHECK ([role] IN ('admin', 'sales_manager', 'account_executive', 'sales_development_rep', 'marketing', 'read_only')),
  [team_id] uuid,
  [manager_id] uuid,
  [timezone] varchar(64) NOT NULL DEFAULT 'UTC',
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [deactivated_at] timestamptz
)
GO

CREATE TABLE [ownership_history] (
  [id] uuid PRIMARY KEY,
  [account_id] uuid,
  [contact_id] uuid,
  [lead_id] uuid,
  [opportunity_id] uuid,
  [from_user_id] uuid,
  [to_user_id] uuid NOT NULL,
  [changed_by] uuid,
  [reason] varchar(200),
  [changed_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [campaigns] (
  [id] uuid PRIMARY KEY,
  [name] varchar(200) NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('email', 'webinar', 'event', 'paid_ads', 'content', 'outbound')),
  [owner_id] uuid NOT NULL,
  [starts_on] date,
  [ends_on] date,
  [budget_cents] bigint,
  [currency] char(3) NOT NULL,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [campaign_members] (
  [id] uuid PRIMARY KEY,
  [campaign_id] uuid NOT NULL,
  [lead_id] uuid,
  [contact_id] uuid,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('targeted', 'sent', 'responded', 'attended', 'unsubscribed')) DEFAULT 'targeted',
  [first_responded_at] timestamptz,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [leads] (
  [id] uuid PRIMARY KEY,
  [owner_id] uuid,
  [first_name] varchar(100),
  [last_name] varchar(100) NOT NULL,
  [email] varchar(254),
  [phone] varchar(30),
  [job_title] varchar(150),
  [company_name] varchar(200),
  [source] nvarchar(255) NOT NULL CHECK ([source] IN ('web_form', 'referral', 'event', 'outbound', 'partner', 'paid_ads', 'list_import')),
  [campaign_id] uuid,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('new', 'working', 'nurturing', 'qualified', 'disqualified', 'converted')) DEFAULT 'new',
  [score] smallint,
  [disqualified_reason] varchar(200),
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [lead_conversions] (
  [lead_id] uuid PRIMARY KEY,
  [account_id] uuid NOT NULL,
  [contact_id] uuid NOT NULL,
  [opportunity_id] uuid,
  [created_account] boolean NOT NULL,
  [created_contact] boolean NOT NULL,
  [converted_by] uuid NOT NULL,
  [converted_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [accounts] (
  [id] uuid PRIMARY KEY,
  [name] varchar(200) NOT NULL,
  [parent_account_id] uuid,
  [owner_id] uuid NOT NULL,
  [type] nvarchar(255) NOT NULL CHECK ([type] IN ('prospect', 'customer', 'former_customer', 'partner', 'competitor')) DEFAULT 'prospect',
  [industry] varchar(100),
  [employee_count] integer,
  [annual_revenue_cents] bigint,
  [website] varchar(300),
  [billing_country] char(2),
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [updated_at] timestamptz NOT NULL DEFAULT (now()),
  [deleted_at] timestamptz
)
GO

CREATE TABLE [account_domains] (
  [domain] varchar(253) PRIMARY KEY,
  [account_id] uuid NOT NULL,
  [is_primary] boolean NOT NULL DEFAULT (false)
)
GO

CREATE TABLE [contacts] (
  [id] uuid PRIMARY KEY,
  [account_id] uuid,
  [owner_id] uuid NOT NULL,
  [first_name] varchar(100),
  [last_name] varchar(100) NOT NULL,
  [email] varchar(254),
  [phone] varchar(30),
  [job_title] varchar(150),
  [department] varchar(100),
  [email_opted_out_at] timestamptz,
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [updated_at] timestamptz NOT NULL DEFAULT (now()),
  [deleted_at] timestamptz
)
GO

CREATE TABLE [pipelines] (
  [id] uuid PRIMARY KEY,
  [name] varchar(100) NOT NULL,
  [is_default] boolean NOT NULL DEFAULT (false),
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [pipeline_stages] (
  [id] uuid PRIMARY KEY,
  [pipeline_id] uuid NOT NULL,
  [name] varchar(100) NOT NULL,
  [position] smallint NOT NULL,
  [probability_pct] smallint NOT NULL,
  [forecast_category] nvarchar(255) NOT NULL CHECK ([forecast_category] IN ('omitted', 'pipeline', 'best_case', 'commit', 'closed')),
  [outcome] nvarchar(255) NOT NULL CHECK ([outcome] IN ('open', 'won', 'lost')) DEFAULT 'open'
)
GO

CREATE TABLE [opportunities] (
  [id] uuid PRIMARY KEY,
  [account_id] uuid NOT NULL,
  [name] varchar(200) NOT NULL,
  [owner_id] uuid NOT NULL,
  [pipeline_id] uuid NOT NULL,
  [stage_id] uuid NOT NULL,
  [price_book_id] uuid,
  [amount_cents] bigint NOT NULL DEFAULT (0),
  [currency] char(3) NOT NULL,
  [close_date] date NOT NULL,
  [probability_pct] smallint NOT NULL,
  [forecast_category] nvarchar(255) NOT NULL CHECK ([forecast_category] IN ('omitted', 'pipeline', 'best_case', 'commit', 'closed')),
  [next_step] varchar(300),
  [lost_reason] varchar(200),
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [closed_at] timestamptz
)
GO

CREATE TABLE [opportunity_stage_history] (
  [id] uuid PRIMARY KEY,
  [opportunity_id] uuid NOT NULL,
  [from_stage_id] uuid,
  [to_stage_id] uuid NOT NULL,
  [amount_cents] bigint NOT NULL,
  [currency] char(3) NOT NULL,
  [close_date] date NOT NULL,
  [probability_pct] smallint NOT NULL,
  [forecast_category] nvarchar(255) NOT NULL CHECK ([forecast_category] IN ('omitted', 'pipeline', 'best_case', 'commit', 'closed')),
  [changed_by] uuid,
  [changed_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [opportunity_contacts] (
  [opportunity_id] uuid NOT NULL,
  [contact_id] uuid NOT NULL,
  [role] nvarchar(255) NOT NULL CHECK ([role] IN ('decision_maker', 'economic_buyer', 'champion', 'influencer', 'technical_evaluator', 'end_user', 'blocker')),
  [is_primary] boolean NOT NULL DEFAULT (false),
  PRIMARY KEY ([opportunity_id], [contact_id])
)
GO

CREATE TABLE [products] (
  [id] uuid PRIMARY KEY,
  [sku] varchar(60) UNIQUE NOT NULL,
  [name] varchar(200) NOT NULL,
  [description] text,
  [family] varchar(100),
  [billing] nvarchar(255) NOT NULL CHECK ([billing] IN ('one_time', 'monthly', 'annual')),
  [is_active] boolean NOT NULL DEFAULT (true),
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [price_books] (
  [id] uuid PRIMARY KEY,
  [name] varchar(100) NOT NULL,
  [currency] char(3) NOT NULL,
  [is_standard] boolean NOT NULL DEFAULT (false),
  [valid_from] date,
  [valid_to] date,
  [is_active] boolean NOT NULL DEFAULT (true)
)
GO

CREATE TABLE [price_book_entries] (
  [id] uuid PRIMARY KEY,
  [price_book_id] uuid NOT NULL,
  [product_id] uuid NOT NULL,
  [list_price_cents] bigint NOT NULL,
  [is_active] boolean NOT NULL DEFAULT (true)
)
GO

CREATE TABLE [opportunity_line_items] (
  [id] uuid PRIMARY KEY,
  [opportunity_id] uuid NOT NULL,
  [product_id] uuid NOT NULL,
  [price_book_entry_id] uuid NOT NULL,
  [quantity] numeric(12,2) NOT NULL,
  [list_price_cents] bigint NOT NULL,
  [unit_price_cents] bigint NOT NULL,
  [discount_pct] numeric(5,2) NOT NULL DEFAULT (0),
  [total_cents] bigint NOT NULL,
  [sort_order] smallint NOT NULL
)
GO

CREATE TABLE [quotes] (
  [id] uuid PRIMARY KEY,
  [opportunity_id] uuid NOT NULL,
  [quote_number] varchar(30) UNIQUE NOT NULL,
  [version] smallint NOT NULL DEFAULT (1),
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('draft', 'sent', 'accepted', 'rejected', 'expired', 'superseded')) DEFAULT 'draft',
  [currency] char(3) NOT NULL,
  [subtotal_cents] bigint NOT NULL,
  [discount_cents] bigint NOT NULL DEFAULT (0),
  [tax_cents] bigint NOT NULL DEFAULT (0),
  [total_cents] bigint NOT NULL,
  [valid_until] date NOT NULL,
  [created_by] uuid NOT NULL,
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [sent_at] timestamptz,
  [accepted_at] timestamptz
)
GO

CREATE TABLE [quote_line_items] (
  [id] uuid PRIMARY KEY,
  [quote_id] uuid NOT NULL,
  [product_id] uuid NOT NULL,
  [description] varchar(300) NOT NULL,
  [quantity] numeric(12,2) NOT NULL,
  [list_price_cents] bigint NOT NULL,
  [unit_price_cents] bigint NOT NULL,
  [discount_pct] numeric(5,2) NOT NULL DEFAULT (0),
  [total_cents] bigint NOT NULL,
  [sort_order] smallint NOT NULL
)
GO

CREATE TABLE [activities] (
  [id] uuid PRIMARY KEY,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('call', 'email', 'meeting', 'task')),
  [subject] varchar(300) NOT NULL,
  [body] text,
  [owner_id] uuid NOT NULL,
  [direction] nvarchar(255) CHECK ([direction] IN ('inbound', 'outbound')),
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('open', 'completed', 'canceled')) DEFAULT 'open',
  [due_at] timestamptz,
  [starts_at] timestamptz,
  [ends_at] timestamptz,
  [completed_at] timestamptz,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [activity_links] (
  [id] uuid PRIMARY KEY,
  [activity_id] uuid NOT NULL,
  [account_id] uuid,
  [contact_id] uuid,
  [lead_id] uuid,
  [opportunity_id] uuid
)
GO

CREATE TABLE [notes] (
  [id] uuid PRIMARY KEY,
  [author_id] uuid NOT NULL,
  [account_id] uuid,
  [contact_id] uuid,
  [lead_id] uuid,
  [opportunity_id] uuid,
  [body] text NOT NULL,
  [is_pinned] boolean NOT NULL DEFAULT (false),
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [updated_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE INDEX [ownership_history_index_0] ON [ownership_history] ("account_id")
GO

CREATE INDEX [ownership_history_index_1] ON [ownership_history] ("contact_id")
GO

CREATE INDEX [ownership_history_index_2] ON [ownership_history] ("lead_id")
GO

CREATE INDEX [ownership_history_index_3] ON [ownership_history] ("opportunity_id")
GO

CREATE UNIQUE INDEX [campaign_members_index_4] ON [campaign_members] ("campaign_id", "lead_id")
GO

CREATE UNIQUE INDEX [campaign_members_index_5] ON [campaign_members] ("campaign_id", "contact_id")
GO

CREATE INDEX [leads_index_6] ON [leads] ("email")
GO

CREATE INDEX [leads_index_7] ON [leads] ("owner_id", "status")
GO

CREATE INDEX [accounts_index_8] ON [accounts] ("owner_id")
GO

CREATE INDEX [accounts_index_9] ON [accounts] ("name")
GO

CREATE INDEX [contacts_index_10] ON [contacts] ("account_id")
GO

CREATE UNIQUE INDEX [contacts_index_11] ON [contacts] ((lower(email)))
GO

CREATE UNIQUE INDEX [pipeline_stages_index_12] ON [pipeline_stages] ("pipeline_id", "position")
GO

CREATE UNIQUE INDEX [pipeline_stages_index_13] ON [pipeline_stages] ("pipeline_id", "name")
GO

CREATE INDEX [opportunities_index_14] ON [opportunities] ("owner_id", "close_date")
GO

CREATE INDEX [opportunities_index_15] ON [opportunities] ("stage_id")
GO

CREATE INDEX [opportunities_index_16] ON [opportunities] ("account_id")
GO

CREATE INDEX [opportunity_stage_history_index_17] ON [opportunity_stage_history] ("opportunity_id", "changed_at")
GO

CREATE UNIQUE INDEX [price_book_entries_index_18] ON [price_book_entries] ("price_book_id", "product_id")
GO

CREATE UNIQUE INDEX [quotes_index_19] ON [quotes] ("opportunity_id", "version")
GO

CREATE INDEX [activities_index_20] ON [activities] ("owner_id", "status", "due_at")
GO

CREATE INDEX [activity_links_index_21] ON [activity_links] ("activity_id")
GO

CREATE INDEX [activity_links_index_22] ON [activity_links] ("account_id")
GO

CREATE INDEX [activity_links_index_23] ON [activity_links] ("contact_id")
GO

CREATE INDEX [activity_links_index_24] ON [activity_links] ("lead_id")
GO

CREATE INDEX [activity_links_index_25] ON [activity_links] ("opportunity_id")
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Sales teams. The hierarchy is what forecast roll-ups and pipeline reviews are grouped by.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'teams';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. EMEA Mid-Market, Inside Sales',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'teams',
@level2type = N'Column', @level2name = 'name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Teams roll up into regions, so a forecast can be read at any level',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'teams',
@level2type = N'Column', @level2name = 'parent_team_id';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'People who use the CRM. Every account, contact, lead and opportunity has an owner here.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'users';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Reps leave; their records are reassigned, never orphaned or deleted',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'users',
@level2type = N'Column', @level2name = 'deactivated_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Who owned which record, and when. Exactly one of the four record columns is set (CHECK num_nonnulls(...) = 1). Commission disputes, territory moves and "who was working this deal in Q2?" are all answered here, because the owner_id on the record only knows the present.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'ownership_history';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for the first assignment',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'ownership_history',
@level2type = N'Column', @level2name = 'from_user_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for assignment rules and round-robin routing',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'ownership_history',
@level2type = N'Column', @level2name = 'changed_by';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. territory realignment, rep left, round-robin',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'ownership_history',
@level2type = N'Column', @level2name = 'reason';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Marketing efforts that produce leads: a webinar, a trade show, a paid search push.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'campaigns';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Who a campaign reached. Exactly one of lead_id or contact_id is set, since campaigns target existing customers too.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'campaign_members';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Unqualified interest, kept apart from contacts. Leads are noisy (form fills, badge scans, list imports) and most never convert; mixing them into contacts pollutes every customer report and count.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'leads';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null while unassigned in the routing queue',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'leads',
@level2type = N'Column', @level2name = 'owner_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Free text. A lead has a company NAME, not an account; the account is created or matched at conversion.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'leads',
@level2type = N'Column', @level2name = 'company_name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'First-touch campaign, kept for attribution',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'leads',
@level2type = N'Column', @level2name = 'campaign_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Fit and engagement score, 0 to 100',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'leads',
@level2type = N'Column', @level2name = 'score';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Where a qualified lead went. The lead row stays, read-only, so its source and campaign are credited with any revenue the opportunity later wins.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'lead_conversions';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null when the lead converted without a deal yet',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'lead_conversions',
@level2type = N'Column', @level2name = 'opportunity_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'False when the lead was matched to an existing account',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'lead_conversions',
@level2type = N'Column', @level2name = 'created_account';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Companies you sell to, partner with or compete against.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'accounts';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Subsidiary to parent, for account hierarchies and roll-ups',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'accounts',
@level2type = N'Column', @level2name = 'parent_account_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'ISO 3166-1 alpha-2. Territory rules key off it.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'accounts',
@level2type = N'Column', @level2name = 'billing_country';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Email domains an account owns. New leads, contacts and logged emails are matched to accounts by domain; free-mail domains are excluded in app code.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'account_domains';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Lowercase, e.g. example.com',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'account_domains',
@level2type = N'Column', @level2name = 'domain';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Qualified people, usually at an account. Their role on a specific deal lives on opportunity_contacts.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'contacts';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for an individual with no company',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'contacts',
@level2type = N'Column', @level2name = 'account_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Consent is a timestamp, not a boolean, so you can prove when it was withdrawn',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'contacts',
@level2type = N'Column', @level2name = 'email_opted_out_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A sales process. New business and renewals rarely share the same stages.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'pipelines';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. New business, Renewals, Partner deals',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'pipelines',
@level2type = N'Column', @level2name = 'name';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Stages as DATA, not an enum, so sales ops can add, rename and reorder them per pipeline without a migration. Reports read outcome and forecast_category, never the stage name.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'pipeline_stages';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. Discovery, Demo, Proposal, Negotiation, Closed won',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'pipeline_stages',
@level2type = N'Column', @level2name = 'name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Default win probability, 0 to 100, for weighted pipeline',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'pipeline_stages',
@level2type = N'Column', @level2name = 'probability_pct';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Default bucket for deals entering this stage',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'pipeline_stages',
@level2type = N'Column', @level2name = 'forecast_category';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Whether reaching this stage closes the deal',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'pipeline_stages',
@level2type = N'Column', @level2name = 'outcome';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A deal: an amount, a close date and a stage. Only the current values live here; how they moved over time is in opportunity_stage_history.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'opportunities';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. Example Corp, 250 seats, FY27',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'opportunities',
@level2type = N'Column', @level2name = 'name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Chosen when the first product is added; sets the currency',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'opportunities',
@level2type = N'Column', @level2name = 'price_book_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Sum of line items, or entered by hand on a deal with no products yet',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'opportunities',
@level2type = N'Column', @level2name = 'amount_cents';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Expected close date while open, actual once closed',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'opportunities',
@level2type = N'Column', @level2name = 'close_date';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Starts from the stage default; the rep may override it',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'opportunities',
@level2type = N'Column', @level2name = 'forecast_category';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Append-only. A row is written whenever the stage, amount, close date or forecast category changes, carrying the full forecast state after the change. "What did the Q3 commit look like on September 1?" is the latest row per opportunity at or before that instant. Stage conversion rates, deal velocity and slipped close dates all come from here; none of them can be rebuilt from the current row.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'opportunity_stage_history';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null on the first row, when the deal is created',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'opportunity_stage_history',
@level2type = N'Column', @level2name = 'from_stage_id';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The buying committee. The same person can be the champion on one deal and a blocker on the next.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'opportunity_contacts';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'What you sell. Holds no price: prices live in price books.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'products';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. Platform, Add-ons, Services',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'products',
@level2type = N'Column', @level2name = 'family';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Price lists. A standard list per currency plus regional, partner or negotiated books.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'price_books';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. Standard USD, Partner EUR, Education',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'price_books',
@level2type = N'Column', @level2name = 'name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'One standard book per currency',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'price_books',
@level2type = N'Column', @level2name = 'is_standard';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The list price of one product in one price book.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'price_book_entries';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Products on a deal, with prices snapshotted. A later price book change never moves a deal already in the forecast.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'opportunity_line_items';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Snapshot of the entry price when the line was added',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'opportunity_line_items',
@level2type = N'Column', @level2name = 'list_price_cents';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The price actually offered after negotiation',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'opportunity_line_items',
@level2type = N'Column', @level2name = 'unit_price_cents';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A priced offer sent to the customer. Once sent it is never edited: a change is a new version, and the old one becomes superseded.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'quotes';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. Q-2026-00417',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'quotes',
@level2type = N'Column', @level2name = 'quote_number';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Copied from the opportunity line items when the quote is generated, then frozen with it. The document the customer signed must stay exactly as they saw it.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'quote_line_items';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Copied from the product, editable before sending',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'quote_line_items',
@level2type = N'Column', @level2name = 'description';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Calls, emails, meetings and tasks in one table, so a timeline is one query and one ordering.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'activities';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Call notes, meeting agenda, or the email body',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'activities',
@level2type = N'Column', @level2name = 'body';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Who made the call or holds the task',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'activities',
@level2type = N'Column', @level2name = 'owner_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Calls and emails only',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'activities',
@level2type = N'Column', @level2name = 'direction';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Logged calls and emails are created completed',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'activities',
@level2type = N'Column', @level2name = 'status';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Tasks',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'activities',
@level2type = N'Column', @level2name = 'due_at';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Meetings',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'activities',
@level2type = N'Column', @level2name = 'starts_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'One activity, many records. A meeting with two contacts about one deal at one account is one activity and four links, so it shows on every timeline. Each link sets exactly one typed foreign key column (CHECK num_nonnulls(account_id, contact_id, lead_id, opportunity_id) = 1) rather than a record_type plus record_id pair, so the database enforces every link and none can dangle.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'activity_links';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Free-form notes on one record, using the same exactly-one typed foreign key pattern as activity_links.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'notes';
GO

ALTER TABLE [teams] ADD FOREIGN KEY ([parent_team_id]) REFERENCES [teams] ([id])
GO

ALTER TABLE [teams] ADD FOREIGN KEY ([manager_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [users] ADD FOREIGN KEY ([team_id]) REFERENCES [teams] ([id])
GO

ALTER TABLE [users] ADD FOREIGN KEY ([manager_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [ownership_history] ADD FOREIGN KEY ([account_id]) REFERENCES [accounts] ([id])
GO

ALTER TABLE [ownership_history] ADD FOREIGN KEY ([contact_id]) REFERENCES [contacts] ([id])
GO

ALTER TABLE [ownership_history] ADD FOREIGN KEY ([lead_id]) REFERENCES [leads] ([id])
GO

ALTER TABLE [ownership_history] ADD FOREIGN KEY ([opportunity_id]) REFERENCES [opportunities] ([id])
GO

ALTER TABLE [ownership_history] ADD FOREIGN KEY ([from_user_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [ownership_history] ADD FOREIGN KEY ([to_user_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [ownership_history] ADD FOREIGN KEY ([changed_by]) REFERENCES [users] ([id])
GO

ALTER TABLE [campaigns] ADD FOREIGN KEY ([owner_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [campaign_members] ADD FOREIGN KEY ([campaign_id]) REFERENCES [campaigns] ([id])
GO

ALTER TABLE [campaign_members] ADD FOREIGN KEY ([lead_id]) REFERENCES [leads] ([id])
GO

ALTER TABLE [campaign_members] ADD FOREIGN KEY ([contact_id]) REFERENCES [contacts] ([id])
GO

ALTER TABLE [leads] ADD FOREIGN KEY ([owner_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [leads] ADD FOREIGN KEY ([campaign_id]) REFERENCES [campaigns] ([id])
GO

ALTER TABLE [lead_conversions] ADD FOREIGN KEY ([lead_id]) REFERENCES [leads] ([id])
GO

ALTER TABLE [lead_conversions] ADD FOREIGN KEY ([account_id]) REFERENCES [accounts] ([id])
GO

ALTER TABLE [lead_conversions] ADD FOREIGN KEY ([contact_id]) REFERENCES [contacts] ([id])
GO

ALTER TABLE [lead_conversions] ADD FOREIGN KEY ([opportunity_id]) REFERENCES [opportunities] ([id])
GO

ALTER TABLE [lead_conversions] ADD FOREIGN KEY ([converted_by]) REFERENCES [users] ([id])
GO

ALTER TABLE [accounts] ADD FOREIGN KEY ([parent_account_id]) REFERENCES [accounts] ([id])
GO

ALTER TABLE [accounts] ADD FOREIGN KEY ([owner_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [account_domains] ADD FOREIGN KEY ([account_id]) REFERENCES [accounts] ([id])
GO

ALTER TABLE [contacts] ADD FOREIGN KEY ([account_id]) REFERENCES [accounts] ([id])
GO

ALTER TABLE [contacts] ADD FOREIGN KEY ([owner_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [pipeline_stages] ADD FOREIGN KEY ([pipeline_id]) REFERENCES [pipelines] ([id])
GO

ALTER TABLE [opportunities] ADD FOREIGN KEY ([account_id]) REFERENCES [accounts] ([id])
GO

ALTER TABLE [opportunities] ADD FOREIGN KEY ([owner_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [opportunities] ADD FOREIGN KEY ([pipeline_id]) REFERENCES [pipelines] ([id])
GO

ALTER TABLE [opportunities] ADD FOREIGN KEY ([stage_id]) REFERENCES [pipeline_stages] ([id])
GO

ALTER TABLE [opportunities] ADD FOREIGN KEY ([price_book_id]) REFERENCES [price_books] ([id])
GO

ALTER TABLE [opportunity_stage_history] ADD FOREIGN KEY ([opportunity_id]) REFERENCES [opportunities] ([id])
GO

ALTER TABLE [opportunity_stage_history] ADD FOREIGN KEY ([from_stage_id]) REFERENCES [pipeline_stages] ([id])
GO

ALTER TABLE [opportunity_stage_history] ADD FOREIGN KEY ([to_stage_id]) REFERENCES [pipeline_stages] ([id])
GO

ALTER TABLE [opportunity_stage_history] ADD FOREIGN KEY ([changed_by]) REFERENCES [users] ([id])
GO

ALTER TABLE [opportunity_contacts] ADD FOREIGN KEY ([opportunity_id]) REFERENCES [opportunities] ([id])
GO

ALTER TABLE [opportunity_contacts] ADD FOREIGN KEY ([contact_id]) REFERENCES [contacts] ([id])
GO

ALTER TABLE [price_book_entries] ADD FOREIGN KEY ([price_book_id]) REFERENCES [price_books] ([id])
GO

ALTER TABLE [price_book_entries] ADD FOREIGN KEY ([product_id]) REFERENCES [products] ([id])
GO

ALTER TABLE [opportunity_line_items] ADD FOREIGN KEY ([opportunity_id]) REFERENCES [opportunities] ([id])
GO

ALTER TABLE [opportunity_line_items] ADD FOREIGN KEY ([product_id]) REFERENCES [products] ([id])
GO

ALTER TABLE [opportunity_line_items] ADD FOREIGN KEY ([price_book_entry_id]) REFERENCES [price_book_entries] ([id])
GO

ALTER TABLE [quotes] ADD FOREIGN KEY ([opportunity_id]) REFERENCES [opportunities] ([id])
GO

ALTER TABLE [quotes] ADD FOREIGN KEY ([created_by]) REFERENCES [users] ([id])
GO

ALTER TABLE [quote_line_items] ADD FOREIGN KEY ([quote_id]) REFERENCES [quotes] ([id])
GO

ALTER TABLE [quote_line_items] ADD FOREIGN KEY ([product_id]) REFERENCES [products] ([id])
GO

ALTER TABLE [activities] ADD FOREIGN KEY ([owner_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [activity_links] ADD FOREIGN KEY ([activity_id]) REFERENCES [activities] ([id])
GO

ALTER TABLE [activity_links] ADD FOREIGN KEY ([account_id]) REFERENCES [accounts] ([id])
GO

ALTER TABLE [activity_links] ADD FOREIGN KEY ([contact_id]) REFERENCES [contacts] ([id])
GO

ALTER TABLE [activity_links] ADD FOREIGN KEY ([lead_id]) REFERENCES [leads] ([id])
GO

ALTER TABLE [activity_links] ADD FOREIGN KEY ([opportunity_id]) REFERENCES [opportunities] ([id])
GO

ALTER TABLE [notes] ADD FOREIGN KEY ([author_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [notes] ADD FOREIGN KEY ([account_id]) REFERENCES [accounts] ([id])
GO

ALTER TABLE [notes] ADD FOREIGN KEY ([contact_id]) REFERENCES [contacts] ([id])
GO

ALTER TABLE [notes] ADD FOREIGN KEY ([lead_id]) REFERENCES [leads] ([id])
GO

ALTER TABLE [notes] ADD FOREIGN KEY ([opportunity_id]) REFERENCES [opportunities] ([id])
GO

How to use this template

  1. Open the ER diagram to see the tables and how they relate.
  2. Copy it into your workspace. You get your own editable copy, in DBML.
  3. Export it as PostgreSQL, MySQL, or SQL Server DDL, or as Prisma, Drizzle, SQLAlchemy, TypeScript, Zod or C# models.

The copy opens in DB Planner’s ER diagram tool, with the schema as text in the DBML editor beside it. Have a database already? Turn its SQL into an ER diagram instead.

Frequently asked questions

Which table is at the centre of the CRM database schema?
users. It is referenced by 12 other tables: accounts, activities, campaigns, contacts, lead_conversions and 7 more.
How is accounts related to users?
accounts.owner_id references users.id, a many to one relationship. All 59 relationships in the schema are listed on this page.
Which table in the CRM database schema has the most columns?
opportunities, with 16 columns, followed by quotes (15) and leads (14). The schema has 216 columns across 24 tables.
Can I export it to PostgreSQL or MySQL?
Yes. Every DB Planner template exports as DBML, as PostgreSQL, MySQL, or SQL Server DDL, and as C# models.
Is this template free?
Yes. You can open it in the browser without an account, and copy it into your own workspace with a free DB Planner account.
Can I change it after copying it?
Yes. A copy is yours: you can rename tables, add columns, and export it. Changes the author makes later do not affect your copy.