A foreign key is a column, or set of columns, in one table that refers to the primary key of another table. The database refuses changes that would leave the reference pointing at a row that does not exist.
Why it matters
Foreign keys encode relationships directly in the schema, so orders cannot belong to missing customers and comments cannot reference deleted posts. They can also cascade actions, such as deleting child rows when a parent is removed. The trade-off is extra checks on writes, and some very large or sharded systems skip them and enforce rules in application code.
Example
CREATE TABLE orders (
id BIGINT PRIMARY KEY,
customer_id BIGINT NOT NULL
REFERENCES customers(id) ON DELETE RESTRICT
);
Inserting an order with customer_id = 999 fails if no such customer exists.
Common mistakes
- Forgetting to index the foreign key column, which makes joins and parent deletes slow.
- Using
ON DELETE CASCADEcarelessly, so one delete wipes out large amounts of related data. - Mixing column types between the key and the reference, which some systems reject or handle slowly.
Related
Get notified when this term updates
Plus occasional practical tips on uptime and monitoring, nothing else. Unsubscribe anytime.
यह पेज सामान्य जानकारी है, जिसे हमारी संपादकीय टीम ने लिखा है और दस्तावेज़ीकरण बदलने पर अपडेट किया जाता है। सर्वर और प्रदाता अलग-अलग होते हैं, इसलिए बदलाव पहले सुरक्षित तरीके से जाँचें। देखें: संपादकीय नीति और अस्वीकरण.