SQL relationships

I'm trying to learn SQL, specifically for SQL server. One question I have is about defining relationships. I know how to build a relationship graphically (showing that the primary key from one table is the foreign key of another), but I'm not sure how to assert the relationship with an equivalent SQL statement. Is this possible?

Also, what is the purpose of defining a relationship? It seems that for any query I could accomplish the same thing using a JOIN operation.

Any attempt to enlighten me would be most appreciated.
Thanks
 

Math Is Hard

Staff Emeritus
Science Advisor
Gold Member
4,435
22
I'm trying to learn SQL, specifically for SQL server. One question I have is about defining relationships. I know how to build a relationship graphically (showing that the primary key from one table is the foreign key of another), but I'm not sure how to assert the relationship with an equivalent SQL statement. Is this possible?
This should help:
http://msdn.microsoft.com/en-us/library/aa933118(SQL.80).aspx

Also, what is the purpose of defining a relationship? It seems that for any query I could accomplish the same thing using a JOIN operation.
To enforce http://en.wikipedia.org/wiki/Referential_integrity" [Broken].
 
Last edited by a moderator:
316
2
Couldn't understand the first question.. I don't know too much of sql (just enough to get done simple tasks)

Also, what is the purpose of defining a relationship? It seems that for any query I could accomplish the same thing using a JOIN operation.

From experience at work:
Say, I have two tables
Tasks
TaskDetails (contains taskId and more details about task)

If they have no relationship:
One of the records in task get accidentally deleted, SQL wouldn't complain .. and in future either this would cause some trouble or my program that uses this database would crash :(

With relationship:
If I attempt to delete task I would get an error that it cannot be deleted because it is referenced in TaskDetails.
 
Thanks for the succinct answers. I've been thumbing through several books tryong to find those answers!
 

The Physics Forums Way

We Value Quality
• Topics based on mainstream science
• Proper English grammar and spelling
We Value Civility
• Positive and compassionate attitudes
• Patience while debating
We Value Productivity
• Disciplined to remain on-topic
• Recognition of own weaknesses
• Solo and co-op problem solving
Top