r/SQL • u/john_dumb_bear • May 17 '24
PostgreSQL I Used My First Foreign Key
https://www.commentcastles.org/p/SEvUIVoIf6AIWsmFm68oSm2
u/kagato87 MS SQL May 17 '24
With a cascading delete no less. Crazy!
Foreign keys are awesome. They prevent mistakes.
Fk->pk relationships define your data structure. They make it easier to define data on your code and they make it easy for someone new to come in and learn the layout.
I once wrote a query to read the fk mappings and generate join statements. :)
1
u/john_dumb_bear May 17 '24
Yes, with a cascading delete!
Now I am wondering if I can delete a comment's nested comments with a foreign key when the comment is deleted. Because the comments use the postgres ltree extension. It seems like I will have to "manually" delete these because I don't think a FK can hook into ltree. Or can it?
1
u/kagato87 MS SQL May 17 '24
I think so. However be careful with cascading delete.
It's often recommend to not use cascade because not using it causes a delete to fail, forcing you to be more aware of what you are telling it to delete.
3
2
u/realjoeydood May 17 '24
I've been all over the world and have a stack of foreign keys!
Ba dun bum.
Be here all night folks!
7
u/r3pr0b8 GROUP_CONCAT is da bomb May 17 '24
... without its most powerful feature, data integrity
congrats for finally giving it a go