Relational Data Modelling in PostgreSQL

Design tables, keys, relationships and constraints so the database protects your data even when application code has bugs.

Intermediate · about 6 hours · difficulty 3/5

Learn first: SQL Fundamentals

A good schema makes features easy and bugs rare. A bad one haunts every query you write afterwards.

Tables and keys

  • Every table gets a primary key. Choose between auto-incrementing integers and UUIDs (or cuid-style ids) based on whether ids appear in public URLs.
  • Foreign keys link tables and stop orphaned rows. Decide what happens on delete: cascade, restrict or set null.

Relationships

  • One-to-many: a company has many openings.
  • Many-to-many: students and skills, through a join table that can also hold data (proficiency level).
  • One-to-one: a user and a profile, when you want to split rarely used columns.

Constraints are your safety net

NOT NULL, UNIQUE (one application per student per opening), CHECK (cgpa between 0 and 10) and enums or lookup tables for statuses. The database enforces these even if a bug slips through validation.

PostgreSQL features worth knowing

Proper types: timestamptz for times, numeric or integer paise for money (never floats), jsonb for genuinely flexible data, and arrays used sparingly. Normalise first; denormalise later only for measured performance needs.

Pitfalls

  • Storing money as a float, which causes rounding errors in rupee totals.
  • Comma-separated values in one column instead of a join table.
  • Skipping unique constraints and relying on application checks, which fail under concurrent requests.

You are ready to move on when you can draw an ER diagram for the placement portal with all keys and constraints, and explain how the database itself prevents duplicate applications.

Key concepts

  • Primary keys: integer vs UUID
  • Foreign keys and delete rules
  • One-to-many and many-to-many
  • Constraints: NOT NULL, UNIQUE, CHECK
  • Normalisation
  • Money and time types
  • jsonb
  • ER diagrams

Mini project

Design and create the full placement portal schema (users, students, companies, openings, applications, skills) with constraints, then write a script that tries to insert invalid data and confirm the database rejects it.

Check yourself

Why store a stipend of Rs 15,000.50 as integer paise or numeric rather than a floating-point number?

Free resources