How to Design a PostgreSQL Schema Visually (Step-by-Step)
For a developer starting a new PostgreSQL database who would rather draw the tables than write every CREATE TABLE by hand.
On this page
At the end of these steps, your PostgreSQL database has a schema of its own with three related tables. DbSchema shows the tables as an ER diagram: each table as a box, with a line for each key between two tables. You draw each table in DbSchema, and DbSchema runs the SQL that creates the table in PostgreSQL.
- Create a schema for the application.
- Connect DbSchema to the database and import the schema.
- Draw the tables, each with a primary key.
- Drag a foreign key from each referencing column to the column it refers to.
- Test the keys with a few rows.
- Grant the application access, and describe the tables.
- Save the design and share it.
Create a schema for the application
A schema is a named group of tables inside a PostgreSQL database. Two schemas can each hold a table of the same name. To tell the two tables apart, you write the schema name in front of the table name, separated by a dot.
Create the schema in psql or another SQL client:
CREATE SCHEMA school;
Creating a schema needs the CREATE privilege on the database. The owner of the database has that privilege. To see which schemas a database already has, list them with a query.
Connect DbSchema to the database
- On the DbSchema Welcome Screen, which opens when DbSchema starts, choose Connect to Database in Start New.
- Click PostgreSQL, choose New Connection on the right, and press Connect to PostgreSQL.
- In the connection dialog, choose Standard as the Method. Fill in where the server runs, Database User, Password and Database, then press Connect.
- In Reverse Engineer the Database, tick
schoolonly, and press Load. - The schema holds no tables yet, so DbSchema opens the No Tables Found dialog. Choose Continue with an empty model.
DbSchema downloads the PostgreSQL JDBC driver on the first connection. The empty school schema then shows in the tree on the left. DbSchema keeps the schema in a model, its own copy of the schema. While DbSchema is connected, each change that you confirm with OK runs in PostgreSQL at once. The History pane, at the bottom left of the DbSchema window, lists the statements that ran.
Draw the tables
The schema gets three tables: students, courses, and the enrollments that link them. Here are the three tables in SQL:
CREATE TABLE school.students (
student_id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
name varchar(100) NOT NULL
);
CREATE TABLE school.courses (
course_id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
title varchar(100) NOT NULL
);
CREATE TABLE school.enrollments (
student_id integer NOT NULL,
course_id integer NOT NULL,
enrolled_on date,
PRIMARY KEY (student_id, course_id)
);
With GENERATED BY DEFAULT AS IDENTITY, PostgreSQL gives each new row the next number in student_id or course_id. Older scripts use SERIAL for the same numbering. The PostgreSQL manual describes identity columns as the SQL-standard form.
enrollments has no id of its own. A student takes a course once, so the pair of student_id and course_id is the primary key.
Draw students in DbSchema instead of typing it:
- Right-click an empty spot on the diagram and choose Create Table.
- Type
studentsin Table Name. - In the Columns tab, press Add. Type
student_id, chooseinteger, tick Primary Key, choose GENERATED BY DEFAULT AS IDENTITY in the list beside Unsigned, and press OK. - Press Add again for
name. Choosevarchar, type 100 in Length, tick Mandatory ( Not Null ), and press OK. - Press OK in the table dialog.
Draw courses the same way. For enrollments, add its three columns without ticking Primary Key, then set the two-column key in the table dialog:
- Open the Primary Key / Unique / Indexes tab and press Add.
- Choose Primary Key.
- Press Add under Columns for
student_id, and again forcourse_id. - Press OK in both dialogs.
Each OK in the table dialog creates the table in PostgreSQL. To read the CREATE TABLE statement before it runs, press SQL at the bottom of the table dialog.
Why the table names in SQL start with school
Without a schema name, PostgreSQL looks for a table along the search path, a list of schemas that it tries in order. The default path of a new database is this:
SHOW search_path;
| search_path |
|---|
| "$user", public |
"$user" stands for a schema named after your login role. PostgreSQL skips that entry when no such schema exists. A name without a schema in front therefore reaches only the public schema, and the school tables are not in public:
SELECT * FROM students;
ERROR: relation "students" does not exist
LINE 1: SELECT * FROM students;
Writing school.students skips the search path. You can also put the schema on the path for your session, and then the short names work:
SET search_path TO school, public;
SELECT count(*) FROM students;
| count |
|---|
| 0 |
A CREATE TABLE without a schema name creates the table in the first schema of the path that exists. By default, that schema is public. Write the schema name in every statement, and no table ends up in public by accident.
Drag the foreign keys
A foreign key makes PostgreSQL refuse a row that points at nothing, such as an enrollment for a student who does not exist. In SQL, these statements add the two foreign keys of enrollments and an index on course_id:
ALTER TABLE school.enrollments
ADD CONSTRAINT fk_student FOREIGN KEY (student_id)
REFERENCES school.students (student_id) ON DELETE CASCADE;
ALTER TABLE school.enrollments
ADD CONSTRAINT fk_course FOREIGN KEY (course_id)
REFERENCES school.courses (course_id);
CREATE INDEX ON school.enrollments (course_id);
In DbSchema, you drag each foreign key on the diagram:
- Drag
student_idofenrollmentsontostudent_idofstudents. The New Foreign Key dialog opens, filled in. - Type
fk_studentin Name, set On Delete to cascade, and press OK. - Drag
course_idofenrollmentsontocourse_idofcourses, and typefk_coursein Name. - On the Optimizations tab, tick Optimize deletions by indexing the referring column(s), and press OK.
DbSchema draws each foreign key as a line between the two tables. With cascade, deleting a student also deletes the student's enrollments. fk_course keeps the default action, noAction, so PostgreSQL refuses to delete a course that still has enrollments.
PostgreSQL creates no index for a foreign key. When you delete a course, PostgreSQL looks in enrollments for rows with that course_id, and the index makes that search fast. The box in step 4 makes DbSchema create the index. student_id needs no index of its own, because it is the first column of the primary key, and the primary key's index covers a search by student_id. The foreign keys article explains the other On Delete actions.
Test the keys with a few rows
Add one student, one course and one enrollment:
INSERT INTO school.students (name) VALUES ('Ada');
INSERT INTO school.courses (title) VALUES ('Databases');
INSERT INTO school.enrollments (student_id, course_id) VALUES (1, 1);
PostgreSQL numbered Ada 1 and the course 1. An enrollment in course 2 fails, because no such course exists:
INSERT INTO school.enrollments (student_id, course_id) VALUES (1, 2);
ERROR: insert or update on table "enrollments" violates foreign key constraint "fk_course"
DETAIL: Key (course_id)=(2) is not present in table "courses".
Enrolling Ada in course 1 a second time breaks the two-column primary key:
INSERT INTO school.enrollments (student_id, course_id) VALUES (1, 1);
ERROR: duplicate key value violates unique constraint "enrollments_pkey"
DETAIL: Key (student_id, course_id)=(1, 1) already exists.
fk_course has the default action, noAction, so deleting the course fails:
DELETE FROM school.courses WHERE course_id = 1;
ERROR: update or delete on table "courses" violates foreign key constraint "fk_course" on table "enrollments"
DETAIL: Key (course_id)=(1) is still referenced from table "enrollments".
Deleting Ada succeeds, and the cascade deletes her enrollment:
DELETE FROM school.students WHERE student_id = 1;
SELECT count(*) FROM school.enrollments;
| count |
|---|
| 0 |
The course Databases stays in courses.
Give the application access to the schema
An application should connect with a role of its own. Create the role, and grant it the tables:
CREATE ROLE school_app LOGIN;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA school TO school_app;
The table grants are not enough. Switch your session to the new role with SET ROLE, and read a table:
SET ROLE school_app;
SELECT course_id, title FROM school.courses;
ERROR: permission denied for schema school
LINE 1: SELECT course_id, title FROM school.courses;
A role needs the USAGE privilege on a schema before it can use anything in the schema. Switch back to your own role with RESET ROLE, and grant the privilege:
RESET ROLE;
GRANT USAGE ON SCHEMA school TO school_app;
SET ROLE school_app;
SELECT course_id, title FROM school.courses;
RESET ROLE;
| course_id | title |
|---|---|
| 1 | Databases |
ALL TABLES IN SCHEMA covers the tables that exist when the grant runs. Run the grant again after you add a table.
Describe the tables and columns
A column name doesn't say that the column holds personal data. A comment on the column says so, and PostgreSQL stores the comment with the column:
COMMENT ON TABLE school.enrollments IS 'One row per student per course';
COMMENT ON COLUMN school.students.name IS 'Personal data';
PostgreSQL keeps one comment per object, and a new COMMENT replaces the old one. Two built-in functions read the comments back:
SELECT obj_description('school.enrollments'::regclass) AS table_comment,
col_description('school.students'::regclass, 2) AS column_comment;
| table_comment | column_comment |
|---|---|
| One row per student per course | Personal data |
::regclass turns a table's name into the table's internal id. The 2 in col_description is the position of name in students.
In DbSchema, type the table's comment in the Comment box above the tabs of the table dialog, and a column's comment in the column dialog. DbSchema keeps the comments in its model and, while connected, writes them to PostgreSQL as COMMENT ON statements. The documentation that DbSchema generates shows them too.
Design without a database, and deploy later
If the database doesn't exist yet, choose Design from Scratch on the Welcome Screen, click PostgreSQL, and press Start Design. DbSchema keeps the design in its model, and nothing reaches PostgreSQL. To stop a connected model from changing the database, choose Database → Offline (connect later).
To create the design in PostgreSQL later, choose Database → Create or Upgrade Model in the Database. DbSchema shows each statement in the Execute Script In Database Dialog before it runs, and Execute runs it. Database → Refresh Model from Database brings changes from the database into the model, such as a table that someone added with a migration script. Both are part of schema synchronization, which needs DbSchema Pro.
Save the design and share it
DbSchema saves the design as a .dbs model file, with the tables, the foreign keys, the diagrams and the comments. Save the model with File → Save Model to File. Saving the model to a file needs DbSchema Pro. Keep the file in the application's Git repository: File → Git Collaboration clones, commits, pushes and pulls without another Git program, as the Git documentation shows.
For readers who don't run DbSchema, choose File → Export As... → HTML5/PDF Documentation, and pick HTML5, PDF or Markdown. The HTML5 page opens in any browser, with the diagram and the comments of every table and column. In the Community Edition, the documentation covers a diagram of up to 12 tables, and the diagram image carries "DbSchema Trial" across it. DbSchema Pro documents any diagram. Generating database documentation walks through the export.
To draw your own schema, download DbSchema at https://dbschema.com/download.html and connect it to your PostgreSQL database. The free Community Edition covers the connection, the diagram, tables and foreign keys drawn on a live database, and the SQL Editor. Saving the model to a file and synchronizing it with the database need DbSchema Pro, which the 15-day trial includes.