Self-Referencing Relationship in ERD Design

How to model a self-referencing (recursive) relationship in an ER diagram. Covers employee-manager hierarchies, category trees, and comment threading.

Relationship Types

Detailed Explanation

When a Table References Itself

A self-referencing relationship (also called a recursive relationship) occurs when a foreign key in a table points back to the primary key of the same table. This is used to model hierarchical or tree-like structures within a single entity.

The Classic Example: Employee-Manager

CREATE TABLE employees (
  id SERIAL PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  title VARCHAR(255),
  manager_id INT,
  FOREIGN KEY (manager_id) REFERENCES employees(id)
);

Here, manager_id references employees.id. The CEO has manager_id = NULL (no manager), and every other employee references their direct manager. This creates a tree structure:

CEO (manager_id = NULL)
├── VP Engineering (manager_id = 1)
│   ├── Tech Lead (manager_id = 2)
│   └── Tech Lead (manager_id = 2)
└── VP Sales (manager_id = 1)
    └── Sales Rep (manager_id = 4)

Other Self-Referencing Patterns

Category tree:

CREATE TABLE categories (
  id SERIAL PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  parent_id INT,
  FOREIGN KEY (parent_id) REFERENCES categories(id)
);

Comment threading:

CREATE TABLE comments (
  id SERIAL PRIMARY KEY,
  post_id INT NOT NULL,
  parent_comment_id INT,
  content TEXT NOT NULL,
  FOREIGN KEY (parent_comment_id) REFERENCES comments(id)
);

Social network (follows):

CREATE TABLE user_follows (
  follower_id INT NOT NULL,
  following_id INT NOT NULL,
  PRIMARY KEY (follower_id, following_id),
  FOREIGN KEY (follower_id) REFERENCES users(id),
  FOREIGN KEY (following_id) REFERENCES users(id)
);

ERD Representation

In the ERD editor, self-referencing relationships are modeled by creating a relationship from an entity back to itself. The from-column (e.g., manager_id) and to-column (e.g., id) both belong to the same entity. The relationship line forms a loop from the entity back to itself.

Key Considerations

  • Nullable FK: The foreign key must be nullable to allow root nodes (no parent)
  • Circular references: Be careful not to create cycles (employee A manages B who manages A)
  • Query performance: Deep hierarchies can require recursive queries (WITH RECURSIVE in SQL)

Use Case

You are modeling organizational hierarchies (employee-manager), category trees (e-commerce product categories), threaded comments (forums, social media), or any data structure where records of the same type form parent-child relationships.

Try It — ERD Editor

Open full tool