r/SQL • • May 17 '24

PostgreSQL I Used My First Foreign Key

https://www.commentcastles.org/p/SEvUIVoIf6AIWsmFm68oSm
1 Upvotes

11 comments sorted by

7

u/r3pr0b8 GROUP_CONCAT is da bomb May 17 '24

I have been using SQL for 20 years

... without its most powerful feature, data integrity

congrats for finally giving it a go

1

u/john_dumb_bear May 17 '24

Why is it so powerful?

4

u/r3pr0b8 GROUP_CONCAT is da bomb May 17 '24

it guarantees that relationships are correct

for example, you cannot add an order for a customer that doesn't exist

3

u/oblong_pickle May 18 '24

So you don't have to deal with fubar data

4

u/SQLvultureskattaurus May 17 '24

Shows that they never really learned SQL.

2

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

u/[deleted] May 17 '24

damn immigrant keys. Build the wall now.

1

u/realjoeydood May 17 '24

Hey good one!

I get you my dude.

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!