60

How do you create a one to many relationship using SQL Server?

1
  • 16
    My professor at USC told us this simple rule: when there is one to many relationship, put the key of 'one' side as foreign key on the 'many' side. And when there is many to many relationship, put both keys as foreign keys in a third table. Aug 2, 2017 at 22:22

5 Answers 5

88
  1. Define two tables (example A and B), with their own primary key
  2. Define a column in Table A as having a Foreign key relationship based on the primary key of Table B

This means that Table A can have one or more records relating to a single record in Table B.

If you already have the tables in place, use the ALTER TABLE statement to create the foreign key constraint:

ALTER TABLE A ADD CONSTRAINT fk_b FOREIGN KEY (b_id) references b(id) 
  • fk_b: Name of the foreign key constraint, must be unique to the database
  • b_id: Name of column in Table A you are creating the foreign key relationship on
  • b: Name of table, in this case b
  • id: Name of column in Table B
6
  • 2
    what is the easiest way to "Define a column in Table A as having a Foreign key relationship based on the primary key of Table B"
    – Tim
    Aug 20, 2009 at 19:35
  • 2
    @George: Updated to include the ALTER TABLE ADD CONSTRAINT command, assuming tables exist.
    – OMG Ponies
    Aug 20, 2009 at 19:54
  • 7
    I think this should be: ALTER TABLE A ADD CONSTRAINT fk_b FOREIGN KEY ( b_id ) references b(id)
    – AceMark
    Sep 1, 2013 at 5:16
  • 1
    Yes, make sure to put fk_b after CONSTRAINT and not FOREIGN KEY.
    – Bondolin
    Dec 5, 2013 at 13:53
  • 1
    As an addendum to an otherwise great answer, one needs to make sure there are no orphaned records in table A before executing the statement. Nov 18, 2014 at 13:28
64

This is a simple example of a classic Order example. Each Customer can have multiple Orders, and each Order can consist of multiple OrderLines.

You create a relation by adding a foreign key column. Each Order record has a CustomerID in it, that points to the ID of the Customer. Similarly, each OrderLine has an OrderID value. This is how the database diagram looks:

enter image description here

In this diagram, there are actual foreign key constraints. They are optional, but they ensure integrity of your data. Also, they make the structure of your database clearer to anyone using it.

I assume you know how to create the tables themselves. Then you just need to define the relationships between them. You can of course define constraints in T-SQL (as posted by several people), but they're also easily added using the designer. Using SQL Management Studio, you can right-click the Order table, click Design (I think it may be called Edit under 2005). Then anywhere in the window that opens right-click and select Relationships.

You will get another dialog, on the right there should be a grid view. One of the first lines reads "Tables and Columns Specification". Click that line, then click again on the little [...] button that appears on the right. You will get this dialog:

Foreign key constraint

The Order table should already be selected on the right. Select the Customer table on the left dropdown. Then in the left grid, select the ID column. In the right grid, select the CustomerID column. Close the dialog, and the next. Press Ctrl+S to save.

Having this constraint will ensure that no Order records can exist without an accompanying Customer record.

To effectively query a database like this, you might want to read up on JOINs.

1
  • I believe I may have downvoted this in error. I do not see nor remember any good reason I would've done so, and would appreciate if you (or someone on your behalf) could make a dummy edit so I could undo my vote. (if you're wondering how I can accidentally vote in the first place... well, you and me both honestly. I don't see anything wrong with the answer though) May 20, 2022 at 17:29
5

This is how I usually do it (sql server).

Create Table Master (
MasterID int identity(1,1) primary key,
Stuff varchar(10)
)
GO
Create Table Detail (
DetailID int identity(1,1) primary key,
MasterID int references Master, --use 'references'
Stuff varchar(10))
GO
Insert into Master values('value')
--(1 row(s) affected)
GO
Insert into Detail values (1, 'Value1') -- Works
--(1 row(s) affected)
insert into Detail values (2, 'Value2') -- Fails
--Msg 547, Level 16, State 0, Line 2
--The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Detail__MasterID__0C70CFB4". 
--The conflict occurred in database "Play", table "dbo.Master", column 'MasterID'.
--The statement has been terminated.

As you can see the second insert into the detail fails because of the foreign key. Here's a good weblink that shows various syntax for defining FK during table creation or after.

http://www.1keydata.com/sql/sql-foreign-key.html

2

If you are not using SSMS then here is the syntax:

ALTER TABLE <table_name>
ADD <constraint_name> FOREIGN KEY 
(<column_name1> ,
<column_name2> )
REFERENCES <table_name>
(<column_name1> ,
<column_name2>)

http://infogoal.com/sql/sql-add-foreignkey.htm

0

If you are talking about two kinds of enitities, say teachers and students, you would create two tables for each and a third one to store the relationship. This third table can have two columns, say teacherID and StudentId. If this is not what you are looking for, please elaborate your question.

4
  • 2
    I don't think this is what I want. I normalized a table and now I want to create a relationship.
    – Tim
    Aug 20, 2009 at 19:38
  • 9
    down-vote due to the provided solution is one for a many-to-many relationship. Even if using for a one-to-many, this is extra overhead when having to run joins. Plus you have to inner join across 3 tables, thus more to type.
    – andrewWinn
    Aug 20, 2009 at 19:40
  • 1
    This one is used to create m-n relationship :) Jan 14, 2011 at 20:37
  • 1
    It's unnecessary. It's recommended to create third table when we have many to many relationships Nov 29, 2019 at 15:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.