SQL schema diagram (D2)

The sql_table shape turns D2 into a perfectly good schema diagramming tool, with primary and foreign key constraints marked.


#What this example shows

  • shape: sql_table, with a type per column.

  • constraint: primary_key and foreign_key markers.

  • Connections drawn between specific columns.


#A worked example

Open it, edit it, or copy the source below.

SQL schema diagram (D2)

The source, which you can paste into a new diagram and edit:

direction: right

customers: {
  shape: sql_table
  id: uuid {constraint: primary_key}
  email: text {constraint: unique}
  name: text
  created_at: timestamptz
}

orders: {
  shape: sql_table
  id: uuid {constraint: primary_key}
  customer_id: uuid {constraint: foreign_key}
  status: text
  total: numeric(10,2)
  placed_at: timestamptz
}

order_items: {
  shape: sql_table
  id: uuid {constraint: primary_key}
  order_id: uuid {constraint: foreign_key}
  product_id: uuid {constraint: foreign_key}
  quantity: int
  unit_price: numeric(10,2)
}

products: {
  shape: sql_table
  id: uuid {constraint: primary_key}
  sku: text {constraint: unique}
  name: text
  price: numeric(10,2)
}

customers.id -> orders.customer_id
orders.id -> order_items.order_id
products.id -> order_items.product_id

#Making it your own

  • Connect specific columns, not whole tables; the diagram is far clearer for it.

  • Constraints are markers, not validation. They document intent.

  • For a schema that generates DDL, DBML is the better tool.



Nesting is the whole idea.