Mermaid ER Diagram Syntax
Entity relationship diagrams map database schemas visually. Each entity is a table, each attribute is a column, and the lines between entities show how tables relate through foreign keys. Mermaid’s ER syntax lets you define all of this in plain text and see the rendered diagram update as you type.
Entities and Attributes
Define an entity with its attributes inside curly braces:
erDiagram
USER {
int id PK
string email UK
string name
string password_hash
timestamp created_at
}
Each attribute line has three parts: type name constraint. The constraint (PK, FK, UK) is optional.
Relationships
Relationships connect entities and specify cardinality:
CUSTOMER ||--o{ ORDER : "places"
This reads as: one CUSTOMER places zero or more ORDERs. The label after the colon describes the relationship verb.
Cardinality Symbols
| Left side | Symbol | Meaning |
|---|---|---|
| Exactly one | || | Must exist, exactly one |
| Zero or one | o| | Optional, at most one |
| One or more | }| | Must exist, one or more |
| Zero or more | }o | Optional, any number |
The relationship line is -- between the two sides. So ||--o{ means “exactly one on the left, zero or more on the right.”
Common Patterns
| Relationship | Syntax | Example |
|---|---|---|
| One to many | ||--o{ | Customer to Orders |
| Many to one | }o--|| | OrderLines to Product |
| One to one | ||--|| | User to UserProfile |
| Many to many (via junction) | Two ||--o{ through a junction entity | Student to Course via Enrollment |
Modeling Patterns
One to many (the most common)
erDiagram
AUTHOR ||--o{ BOOK : writes
AUTHOR {
int id PK
string name
}
BOOK {
int id PK
int author_id FK
string title
date published
}
Self-referencing
erDiagram
EMPLOYEE ||--o{ EMPLOYEE : "manages"
EMPLOYEE {
int id PK
int manager_id FK
string name
string role
}
Many to many through junction
erDiagram
STUDENT }o--|| ENROLLMENT : enrolls
ENROLLMENT ||--o{ COURSE : "enrolled in"
STUDENT {
int id PK
string name
}
ENROLLMENT {
int id PK
int student_id FK
int course_id FK
date enrolled_at
string grade
}
COURSE {
int id PK
string title
int credits
}
Always model many-to-many as two one-to-many relationships through an explicit junction table. This matches the actual database schema and lets you add attributes to the junction (enrolled_at, grade, etc.).
Tips for Readable ER Diagrams
Keep entity names uppercase and singular (USER not users). Use short, descriptive relationship labels. Put the “parent” entity on the left side of the relationship (the one with ||). For large schemas, break the diagram into domain-specific sections rather than cramming everything into one diagram.
For documenting API interactions with these entities, try the Mermaid Sequence Diagram. For process flows that operate on this data, use the Mermaid Flowchart.