From CREATE TABLE statements to automated PK & FK relationships in ER diagram.
Quick start
Read the blog: SQL Diagram (Part 3): SQL-to-ERD with DDL
Best practice: Some DDL syntax is currently not supported.
If you don't see the diagram, please simplify complex settings in your schema to include only column names and data types.
Example:
CREATE TABEL {{name}} (
{{name}} TYPE
)
Learn SQL CREATE TABLE Statement:
CREATE TABLE users(
id INT AUTO_INCREMENT UNIQUE PRIMARY KEY,
username VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE photos(
id INT AUTO_INCREMENT PRIMARY KEY,
image_url VARCHAR(355) NOT NULL,
user_id INT NOT NULL,
created_dat TIMESTAMP DEFAULT NOW(),
FOREIGN KEY(user_id) REFERENCES users(id) -- 👈 Relation
);
Using REFERENCES
Learn more: https://www.w3schools.com/sql/sql_foreignkey.asp
FOREIGN KEY(...) REFERENCES my_table(...)
CREATE TABLE comments(
id INT AUTO_INCREMENT PRIMARY KEY,
comment_text VARCHAR(255) NOT NULL,
user_id INT NOT NULL,
photo_id INT NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
FOREIGN KEY(user_id) REFERENCES users(id), -- 👈 Relation
FOREIGN KEY(photo_id) REFERENCES photos(id)
);
Adding CONSTRAINT
ADD CONSTRAINT ... FOREIGN KEY(...) REFERENCES my_table(...)
CREATE TABLE sports(
sport_id INT,
sport_name VARCHAR(255) NOT NULL,
PRIMARY KEY(sport_id)
);
CREATE TABLE person(
person_id INT,
PRIMARY KEY(person_id),
);
ALTER TABLE person
ADD CONSTRAINT fk_sport_id
FOREIGN KEY(sport_id) REFERENCES sports(sport_id); -- 👈 Relation
SQL+DDL in the same query
Using DDL for schema and identify relationship from SQL JOINs:
FROM a INNER JOIN b ON a.id = b.id
SELECT *
FROM my_table
INNER JOIN another_table ON my_table.id = another_table.id; -- 👈 Relation
-- DDLs
CREATE TABLE my_table (
id INT,
name VARCHAR(255)
);
CREATE TABLE another_table (
id INT,
description TEXT
);
-- Using REFERENCES
CREATE TABLE new_table (
id INT UNIQUE PRIMARY KEY,
another_id INT NOT NULL,
FOREIGN KEY (another_id) REFERENCES another_table(id), -- 👈 Relation
);
Last updated