SQL to ER Diagram
Operator: Abdulla Al Fahad. How tools are built and checked
A schema is easiest to discuss when you can see it: which tables hang off which, where the join tables are, whether that nullable foreign key is really optional. This page reads CREATE TABLE statements and draws one box per table, with the columns, their types, the primary key, and a crow's-foot line for every foreign key. You can drag the boxes into a layout that makes sense for the conversation, then save the picture as SVG or PNG or copy the same schema out as Mermaid or DBML text.
The SQL is parsed by a small parser written for this page, not sent to a database or a server. It reads the dialect features that show up in real dumps from PostgreSQL, MySQL and MariaDB, SQLite and SQL Server, and it tells you in plain words which statements it skipped instead of failing on them. A schema with 150 tables is the most it will draw.
Key features
- Paste DDL or open a .sql file, with samples for PostgreSQL, MySQL, SQLite and SQL Server
- Layered automatic layout: referenced tables on the left, the tables that point at them on the right, unrelated tables in a grid below
- Drag any table with a mouse or finger; the lines follow, and Reset layout restores the automatic arrangement
- Crow's-foot relationship lines with one, zero-or-one and many ends, dashed for non-identifying references
- PK, FK and UQ badges, column types right-aligned, a trailing ? on a type for columns that accept NULL
- Save SVG, or PNG at 1x to 4x (lowered automatically when the image would pass the browser's canvas limit)
- Copy or download the schema as a Mermaid erDiagram or as DBML with Table blocks and Ref lines
Which DDL is read, and which statements are skipped
What is understood: CREATE TABLE (with IF NOT EXISTS, TEMP, UNLOGGED and similar words in front of TABLE), columns with their types and parameters (varchar(255), numeric(10,2), double precision, timestamp with time zone, int unsigned, enum('a','b'), nvarchar(max), int[]), NOT NULL, PRIMARY KEY, UNIQUE, DEFAULT, AUTO_INCREMENT, AUTOINCREMENT, IDENTITY(1,1), GENERATED ... AS IDENTITY and the serial types, plus COMMENT 'text' on a column or table. Identifiers can be bare, "double quoted", `backticked` or [bracketed], and schema-qualified names such as public.orders or [dbo].[Orders] are accepted.
Relationships come from five places: an inline REFERENCES on a column, a table-level FOREIGN KEY (a, b) REFERENCES t (x, y) with any number of columns, a named CONSTRAINT ... FOREIGN KEY, ALTER TABLE ... ADD [CONSTRAINT x] FOREIGN KEY (including SQL Server's WITH CHECK form), and a REFERENCES with no column list, which points at the target's primary key. ON DELETE and ON UPDATE actions are kept and appear in the DBML export. Table-level PRIMARY KEY and UNIQUE constraints, UNIQUE KEY name (cols), CREATE UNIQUE INDEX and ALTER TABLE ... ADD PRIMARY KEY are all folded into the same model.
What is skipped: views, functions, triggers, procedures, plain indexes, INSERT, GRANT, SET, USE and PRAGMA statements, CHECK constraints, exclusion constraints, partition clauses and storage options such as ENGINE=InnoDB or WITHOUT ROWID. Each skipped kind is counted in a note under the editor, for example "Skipped 2 INSERT statements". A foreign key that points at a table that is not in the text is reported with its line number and no line is drawn for it. CREATE TABLE ... AS SELECT and PARTITION OF produce no table.
Cardinality is worked out from the keys, not guessed. The foreign key end is drawn as a fork (zero or many) unless the foreign key columns are themselves the primary key or carry a unique constraint, in which case it is drawn as a bar and a circle (zero or one), a one-to-one link. The referenced end is two bars (exactly one) when every foreign key column is NOT NULL and a bar with a circle (zero or one) when any of them can be NULL. A solid line means the foreign key columns sit inside the child's primary key, as in a join table; a dashed line is an ordinary reference.
Two tables that share a bare name in different schemas are shown as schema.name so they stay distinguishable. Duplicate FOREIGN KEY declarations that repeat the same columns and target are drawn once. The parser reads up to 2,000,000 characters and the file picker accepts files up to 3 MB.
How it works
The text is first cut into tokens: words, quoted identifiers, numbers, strings and symbols, with comments (-- to end of line, /* ... */, and # at the start of a line) removed and dollar-quoted PostgreSQL bodies swallowed whole. A line holding only GO ends the statement, which is how SQL Server dumps separate batches. Statements are then split on semicolons that sit outside parentheses.
Each CREATE TABLE body is split on top-level commas into items. An item that starts with CONSTRAINT, PRIMARY, UNIQUE, FOREIGN or similar is a constraint; anything else is a column. A column's type is the run of words and parenthesised parameters before the first keyword such as NOT, DEFAULT or REFERENCES, which is why double precision and character varying(40) stay in one piece, and MySQL's CHARACTER SET clause is left out of the type. Foreign keys are collected first and resolved after the whole text has been read, so a table can reference one defined further down or added by an ALTER TABLE at the end.
Layout assigns each table a layer one higher than the highest layer among the tables it references, ignoring any edge that would close a loop, so a self-reference such as employees.manager_id does not break anything. Within each layer the tables are reordered a few times by the average position of their neighbours to cut down line crossings, and a layer taller than about 1,500 pixels wraps into a second column. Box widths come from measuring the real text with a canvas, so long column names are not clipped; anything past 420 pixels is shortened with an ellipsis.
Each relationship leaves the foreign key's own row and arrives at the referenced column's row, as a cubic curve with horizontal tangents so the crow's-foot symbols sit square against the box edge. The preview, the SVG file and the PNG are produced from the same SVG string, so what you see is what you save.
Common use cases
- Drawing the schema of a project you have just inherited, starting from the output of pg_dump --schema-only or mysqldump --no-data
- Adding a diagram to a pull request that changes the database, with the Mermaid text pasted straight into the description
- Checking that a migration really added the foreign key you meant, by looking for the line between the two boxes
- Explaining a data model to a non-developer in a meeting, with the join tables moved next to the tables they join
- Moving a schema into dbdiagram.io or another DBML tool without retyping it
How to use this tool
- Paste your CREATE TABLE statements into the SQL box, or press Open .sql file, or start from one of the four samples.
- Read the notes under the box. They list statements that were skipped and any foreign key whose target table is missing.
- On the Diagram tab, drag tables into a tidy arrangement and pick a zoom; Fit width scales a wide diagram to your screen.
- Choose a PNG scale and press Save PNG, or press Save SVG for a file that stays sharp at any size.
- Open the Mermaid or DBML tab to copy the same schema as text for a README, a pull request or dbdiagram.io.
Example
Two PostgreSQL tables with an inline foreign key
CREATE TABLE authors (
id serial PRIMARY KEY,
name varchar(80) NOT NULL
);
CREATE TABLE books (
id serial PRIMARY KEY,
author_id int NOT NULL REFERENCES authors (id) ON DELETE CASCADE,
title text NOT NULL,
isbn char(13) UNIQUE
);Mermaid and DBML tabs
erDiagram
authors ||..o{ books : "author_id"
authors {
serial id PK
varchar(80) name
}
books {
serial id PK
int author_id FK
text title
char(13) isbn UK
}
Table authors {
id serial [pk, increment]
name varchar(80) [not null]
}
Table books {
id serial [pk, increment]
author_id int [not null]
title text [not null]
isbn char(13) [unique]
}
Ref: books.author_id > authors.id [delete: cascade]
authors.id is drawn with two bars because author_id is NOT NULL; books is drawn with a fork. The dashed line (..) is Mermaid's non-identifying relationship.Tips for best results
- For a large database, paste only the CREATE TABLE and ALTER TABLE ... ADD CONSTRAINT parts of a dump. Data, indexes and function bodies add nothing to the drawing.
- If a table sits far from the tables it points at, drag it; the position is remembered while you keep editing the SQL, and Reset layout clears every move at once.
- If a relationship you expected to be one-to-one is drawn with a fork, check that the foreign key column itself, not some other column, carries the UNIQUE constraint or is the primary key.
- Name your constraints. A named foreign key appears as a named Ref in the DBML output, which makes the exported text easier to review.
- Use Save SVG for documents and slides and PNG for chat. A 3x PNG of a 20-table schema is usually well under the browser's size limit; a very large schema is scaled down, with a note about it.
Edge cases to watch
Only the structure in the text is drawn. If a foreign key exists in the live database but was not in the dump you pasted, it will not appear, and the page cannot connect to a database to look.
A REFERENCES clause without a column list is resolved to the target's primary key. If the target has no primary key in the text, the first column is used, which may be wrong; write the column list explicitly.
Polymorphic and soft references, such as a commentable_id column with a commentable_type column, are not foreign keys in SQL and are not drawn.
Unusual dialect features such as PostgreSQL inheritance, partitioned tables declared with PARTITION OF, and Oracle syntax are not read. The statement is skipped and counted, and the rest of the schema still draws.
Mermaid has a narrower attribute syntax than SQL. In the Mermaid export, spaces in types become underscores (timestamp_with_time_zone), and entity names with dots or spaces are quoted. The DBML export keeps types in quotes instead.
Reading the symbols
At the foreign key end of a line, a fork means one row of the referenced table can be linked from many rows of this one. A bar with a small circle means at most one row can link, which is what you see when the foreign key column is also the primary key, as in a customer_profiles table keyed by customer_id.
At the referenced end, two bars mean every row of the child must point to exactly one parent, because the foreign key is NOT NULL. A bar with a circle means the parent is optional: the column is nullable, so a row may point at nothing. In the orders example from the PostgreSQL sample, customer_id is required but coupon_id is not, and the two lines look different for that reason.
On the Mermaid tab the same information is written as ||, |o, o{ and o| markers around either -- (solid) or .. (dashed). The DBML tab writes it as > (many to one) or - (one to one) in each Ref line.
What stays in your browser
The page makes no request that carries your SQL. Parsing, layout, drawing and both text exports run in the tab, and the SVG and PNG files are built there as well. The only network traffic is the page itself loading.
The text is not saved between visits. Reloading the page returns to the PostgreSQL sample, so keep your own copy of anything you want to come back to.
Frequently asked questions
Which SQL dialects does it read?
PostgreSQL, MySQL and MariaDB, SQLite and SQL Server CREATE TABLE syntax, including backtick and bracket quoting, IDENTITY and AUTO_INCREMENT, and GO batch separators. It is not a full SQL parser: Oracle-specific syntax, partitioned and inherited tables and CREATE TABLE ... AS SELECT are skipped with a note.
Why does a table show up without any lines?
Either it has no foreign keys and nothing references it, or the foreign keys point at tables that are not in the pasted text. Missing targets are listed in the notes under the editor with the line number.
Can I load the diagram into dbdiagram.io?
Yes. Copy the DBML tab and paste it into the editor there. Column types, primary keys, increments, not null, unique, defaults, notes and Ref lines with delete and update actions are included.
Does it handle composite foreign keys?
Yes. FOREIGN KEY (a, b) REFERENCES parent (x, y) draws one line from the first column's row to the first referenced column's row, and the DBML export writes the full pair as child.(a, b) > parent.(x, y).