Menu

Link orders to customers with an enforced, cascading foreign key

customers and orders exist as two separate tables, but nothing stops orders.customer_id from pointing at a customer that doesn't exist — the two tables aren't actually linked at the database level yet.

Add a FOREIGN KEY from orders.customer_id to customers.id. A customer who closes their account should have their orders removed automatically, so the constraint needs ON DELETE CASCADE.

Schema

customers
idINT
nameTEXT
orders
idINT
customer_idINT
amountNUMERIC

Example input

customers
orders
↑ Read the question

Keep going

Company names are trademarks of their respective owners, used here only to describe practice material. mahir_data is not affiliated with, endorsed by, or sponsored by any company named on this site. Terms.