Databases · Schema, Keys & Data Types
Primary and Foreign Keys
Cheat sheet · https://pcornel.dk/topic.php?topic=6167
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 topicpsql -c "SELECT now(), version();"— PostgreSQL reachable and versionmysql -e "SELECT NOW(), VERSION();"— MariaDB/MySQL reachable and versionsqlcmd -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