Pcornel
Databases · Schema, Keys & Data Types

Primary and Foreign Keys

Cheat sheet · https://pcornel.dk/topic.php?topic=6167

Back to the Topic

Answer

A primary key uniquely identifies each row; a foreign key references a primary key in another table so the database enforces relationships.

Remember

Index foreign key columns (MySQL does automatically, PostgreSQL does not). Choose ON DELETE behaviour deliberately (RESTRICT vs CASCADE).

First checks

  • SELECT … LEFT JOIN parent … WHERE parent.id IS NULL — first check for this topic
  • psql -c "SELECT now(), version();" — PostgreSQL reachable and version
  • mysql -e "SELECT NOW(), VERSION();" — MariaDB/MySQL reachable and version
  • sqlcmd -S <server> -Q "SELECT @@VERSION" — SQL Server reachable and version

Verify in this order

row inserted → PK unique check → FK checked against parent

Where it usually breaks

ON DELETE CASCADE can remove large amounts of data unexpectedly.

Read-only verification commands unless stated otherwise. Confirm syntax for your platform and release. Full reference: https://pcornel.dk/topic.php?topic=6167

Confirmation

Confirm action

Continue?