PostgreSQL Foundations·A database you can operate

The relational model and psql

PostgreSQL stores rows in tables and enforces relationships with keys.

Intermediate 13 min read Lesson 6 of 300 Challenge included
What you will be able to do
  • Use meaningful primary keys; UUIDs help when clients create records.
  • Add NOT NULL and CHECK constraints at the database boundary.
  • Use \d and \dt in psql to inspect objects.

In plain English

A primary key identifies a row; a foreign key points at another table. Constraints are executable documentation. psql gives you a direct, reproducible way to inspect schema and data.

schema.sqlSQL
create table courses (
  slug text primary key,
  title text not null,
  published boolean not null default false
);

create table lessons (
  id bigint generated always as identity primary key,
  course_slug text not null references courses(slug) on delete cascade,
  slug text not null,
  title text not null,
  minutes integer not null check (minutes > 0),
  unique (course_slug, slug)
);
Your turn

Create a lessons table

Medium

Create lessons with an identity id, a course_slug foreign key, a slug, a title and positive minutes. Make course_slug + slug unique.

SQL · starter
create table lessons ();
Check your understanding before moving on.
Knowledge checkQuestion 1

What does a foreign key enforce?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 6 of 300 · 0% of course