PGoCareerGoCareer prep tools
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

SQL · Theory

Primary Key vs Foreign Key

← All stacks

Theory

269/439

Primary Key vs Foreign Key

PRIMARY KEY is this table’s identity (students.roll). FOREIGN KEY is a pointer in another table (marks.roll) that must match a parent PK/UNIQUE. Parent first, then child.

You can query without declaring an FK, but then the database will not stop orphans. Declare the FK.

Trap — putting the FK on the parent instead of the child.

On the example next to this theory: Primary Key vs Foreign Key — keys and constraints protect data integrity; indexes speed lookups.

Diagram
  students.id  ← PK (unique)
       ▲
       │ FK
  marks.student_id
Exam tip

students.roll PK. marks.roll FK → students.roll.

Primary Key vs Foreign Key — sample query

CREATE TABLE authors (
  id INTEGER PRIMARY KEY,
  email TEXT UNIQUE NOT NULL
);
CREATE TABLE books (
  id INTEGER PRIMARY KEY,
  author_id INTEGER NOT NULL,
  title TEXT NOT NULL,
  FOREIGN KEY (author_id) REFERENCES authors(id)
);
INSERT INTO authors VALUES (1, 'a@x.com');
INSERT INTO books VALUES (1, 1, 'SQL Basics');
SELECT * FROM books;

Primary Key vs Foreign Key — keys and constraints protect data integrity; indexes speed lookups.

Short notes

  • DefPK identifies a row. FK points at a parent PK.
  • RuleFK lives on the child table.
  • TrapFK on the parent table.

Questions

1

Where do you put the FOREIGN KEY?

269 / 439

P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.