Designing a Schema with Constraints
A schema is only as trustworthy as the rules it enforces. Build a small library database on a live PostgreSQL server with primary keys, foreign keys, NOT NULL, UNIQUE, CHECK and a composite-key join table.
- Intermediate
- 45 min
- SQL
- PostgreSQL
- Schema design
- Databases
Overview
Bad data is far cheaper to prevent than to clean up — and a well-designed schema refuses to store nonsense in the first place. In this lab you connect to a real PostgreSQL server (psql labdb) and build a small library database from scratch.
You'll create tables with primary keys, wire them together with a foreign key, and layer on the constraints that make the database enforce its own integrity: NOT NULL, UNIQUE, and CHECK. You'll finish with a composite-key join table — the standard pattern for many-to-many relationships. Every constraint you add is one class of bug the database will now reject automatically.
What you will learn
- Create tables with
SERIAL PRIMARY KEYcolumns in PostgreSQL - Enforce required and unique values with
NOT NULLandUNIQUE - Link tables with a
FOREIGN KEY(referential integrity) - Reject invalid values with a
CHECKconstraint - Model a many-to-many relationship with a composite primary key
Before you start
- You've seen SQL before (
SELECT/INSERT) - Comfortable in a Linux shell
- No PostgreSQL experience required — the server is already running
Tasks
- 01Create the authors table
- 02Create books with a foreign key and a CHECK
- 03Insert data the constraints accept
- 04Model tags with a composite primary key