Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Introduction to relationships and foreign keys

From: SQL Server 2008 Essential Training

Video: Introduction to relationships and foreign keys

A vital part of designing any database is the ability to create relationships between your tables. Let's go through an example. We have a simple product table, dbo.Product, here. It has its own primary key, the ProductID, which is automatically generating a unique number for each product as it's entered into the database. And one of the benefits of having that primary key is we can use it elsewhere. So we have a different table, this time called OrderItem, helping us construct our orders.

Introduction to relationships and foreign keys

A vital part of designing any database is the ability to create relationships between your tables. Let's go through an example. We have a simple product table, dbo.Product, here. It has its own primary key, the ProductID, which is automatically generating a unique number for each product as it's entered into the database. And one of the benefits of having that primary key is we can use it elsewhere. So we have a different table, this time called OrderItem, helping us construct our orders.

Itself it has its own primary key with its own automatically incremented value, but what's a bit more interesting is it has another column here of ProductID. Now ProductID in OrderItem should reference the ProductID in the Product table, but whereas in the Product table it has to be unique, in OrderItem it doesn't. We could have for example the ProductID 1001 three times in OrderItems, or four times, or a dozen, all referencing the same product.

We could have 1010 pointing to our 1010 product. We could have 1002. This is the relationship that we're talking about between our tables. In the Product table, ProductID is referred to as the primary key. It is unique. In the OrderItem table, ProductID is referred to as a foreign key. It's a key to some other table, allowing us to join our information together. The benefit of having this relationship described is we can go either way we can go from the OrderItem and go and get product details, or we can go from the product and find how many order items have been created for that product.

And when you have a relationship like this it's what's defined as a one-to-many relationship. For every one product we can have many order items. Now you'll end up creating dozens or potentially hundreds of relationships when you design your databases. If you're using SQL Server Management Studio to show a database diagram you'll actually see that relationship defined between the tables. And as you create more-and-more complex databases, you'll find that you're going to have relationships between most of them.

What I'm looking at here is just a zoomed out diagram of the AdventureWorks database and that's not even a particularly large database. It's very, very common to have relationships between your tables. And there really are two main kinds of relationships that we care about. The first one, the most common, what we just explored, the idea of a one-to-many relationship. So one customer many orders, one category has many products in it, one department has many employees. Now bare in mind when you describe a one- to-many relationship you don't actually have to have many. Any one customer might only place one order.

Might even place zero orders, but one customer can have many orders, one category can have many products, one department can have many employees. But the important point is here that at least according to your own business rules the opposite of these statements is not true, that in your business an order has one customer. You don't say an order can have many customers. It can't. An employee has one department. A product has one category. So you can view this either from the top- down or the bottom-up, whatever makes sense.

Now as this is the most common thing that you're going to see when you're looking at a diagram in SQL Server Management Studio, you'll see the relationship defined like this with this icon. The key represents the one and the infinity sign represents the many. So when you're looking at this diagram it doesn't matter whether the tables are shown on top or underneath. What's important is where the key is. The next kind of relationship we can have is called a many-to-many relationship. It's not as common as one-to- many, but it's still quite common.

Now you often have to think about this one, because these business situations can often feel like one-to-many. At first, let's say we have an author table with a list of a few authors inside it and their names, and some kind of key and identity for them, and we also have a title table with the list of book titles. Well at first glance what we might say is okay, this is a one-to-many relationship. We could take the author number 74, Jordan Winters, and say that we want to represent that author has written both book one, DB Design, and book 3, SQL Server.

And we can say that Fred Summers, author number 75, wrote book 2 on SharePoint. And if this was a classic one-to-many relationship, one author, one or more titles, we could add a new column to the title table. This would be an author ID column. It would be a foreign key to the author table. But here is the issue. What happens if in a day, or a week, or a month we say we'll actually the SQL Server book was written by two authors? Well the way that we have it right now, we have that author column can only store one, storing a foreign key to author ID 74.

And this is what we mean by a many-to- many relationship. One author can have many titles, one title can have many authors. Now the way some people try and model this is they'll add a new column to the title table. They'll put in author ID 2 and they'll have that be 76 and pointed to John Marr. However, adding new columns to your tables, and particularly these kind. what are called repeating groups or repeating columns. is a really, really bad idea and it's a definite no-no in database design.

So we'll get rid of that idea. Well some other people think, "Well I'm going to cheat a little bit and I'll just do something quick and dirty and I'll just slide in little set of comma separated values there." So that the author column can point to both 74 and 76, but that's just a cheat and like adding a new column this is not suggested either. In fact we're going to solve this problem by getting rid of the author column entirely. So we go back to two completely detached tables and what we do to fix this is we add another table.

We add what's often referred to as a junction or a linking table. Now the only reason for this table to exist is to join author and title together. So in fact the name of this title by convention would be authortitle. It could also be titleauthor. It doesn't really matter which way round it goes, because what we're going to do is setup two one-to-many relationships. In fact, you cannot, in SQL Server or in any other relational database, you cannot express a many-to-many relationship directly. You can only do two one-to-many relationships.

So what we'll do is we'll define a one-to- many relationship from the author to authortitle. So one author with ID 74 can exist in the AuthorID foreign key column in authortitle twice, or three times, or five times, or a dozen. Using that we can go from author to authortitle, find a TitleID ,and map it up to the title table. And we can also go the other way. We can take the identity of a title like number 3, take it back to the authortitle table to two rows there so one-to-many relationship back the way, grab the AuthorID, and follow that back up to the author table.

So we are expressing now a many-to-many relationship. And if you go looking in say some of the sampled database, whether it's the larger ones like AdventureWorks or even the small ones like AdventureWorksLT, anytime you see a table name that seems to join the name of two other tables-- So we have ProductModel, ProductDescription, and then ProductModelProductDescription. You can make the assumption that the one with a long name is simply there to join ProductModel and ProductDescription together.

In fact, if you want to confirm that what we could do is make a new database diagram. I'm going to add just those three tables that I suspect that from, ProductDescription, I'll hold down Ctrl and select ProductModel and ProductModelProductDescription, click Add, close this, and what I can actually see here is my many-to-many being rendered out. We go from ProductModel is the one, to the many, a ProductModelProductDescription. ProductDescription is the one to the many.

The only reason for the existence of this table is to join the other two together. In a large database you're going to end up with a lot of one-to-many relationships between your tables and a few of those will really be used to create a many-to-many relationship. Officially, there is also a one-to- one relationship that is possible, but it's not common at all. If you think about it, if one row in one table is pointing to one row and only one row in another table, well you might as well just combine them so it's just one row in both places.

Although also bear in mind that if those are the official three kinds of relationships, one-to-many very common, many-to-many quite common, and one-to-one not common at all, you also have what some people consider a fourth kind of relationship. Zoom into any large database diagram and you'll find things like this, a table just existing without any. Some people consider "none" to be a relationship. If you get obsessive about what these relationships are, and again the geek trivia term is the cardinality is what we call something that describes the relationship between tables.

Some people say none is an official relationship. I don't think so, but you'll certainly see that a lot. You don't have to connect your tables to other parts of your database. So the key question is going to be, how do we do this? And we'll see that next.

Show transcript

This video is part of

Image for SQL Server 2008 Essential Training
SQL Server 2008 Essential Training

74 video lessons · 36196 viewers

Simon Allardice

Expand all | Collapse all
  1. 2m 21s
    1. Welcome
      1m 19s
    2. Using the exercise files
      1m 2s
  2. 17m 58s
    1. SQL Server core concepts
      9m 4s
    2. SQL Server editions
      3m 8s
    3. Applications included with SQL Server
      5m 46s
  3. 26m 1s
    1. Preparing for installation
      3m 44s
    2. Creating service accounts
      2m 33s
    3. Installing SQL Server
      11m 42s
    4. Post-installation checks
      3m 9s
    5. Installing sample databases
      4m 53s
  4. 13m 35s
    1. Introduction to SQL Server Management Studio
      8m 7s
    2. Introduction to SQL Server Books Online
      3m 6s
    3. SQL Server system databases
      2m 22s
  5. 1h 26m
    1. Planning your database
      9m 39s
    2. Creating a SQL Server database
      4m 7s
    3. Creating tables
      7m 51s
    4. Data types in SQL Server
      12m 25s
    5. Defining keys
      8m 9s
    6. Creating default values
      4m 39s
    7. Creating check constraints
      2m 25s
    8. Creating unique constraints
      4m 34s
    9. Introduction to relationships and foreign keys
      9m 51s
    10. Creating relationships in SQL Server Management Studio
      8m 14s
    11. Database normalization
      11m 47s
    12. Creating computed columns
      3m 10s
  6. 23m 11s
    1. Using the SQL Server Import and Export Wizard
      3m 58s
    2. Importing Excel files into SQL Server
      6m 11s
    3. Importing CSV files into SQL Server
      5m 27s
    4. Importing Access databases into SQL Server
      7m 35s
  7. 55m 29s
    1. Introduction to Transact-SQL
      3m 43s
    2. Using SELECT statements
      7m 16s
    3. Changing the default database
      2m 21s
    4. Creating conditions in SQL
      8m 10s
    5. Sorting your output
      3m 23s
    6. Using aggregate functions
      7m 12s
    7. Finding unique values
      2m 14s
    8. Joining multiple tables together
      8m 0s
    9. Using subqueries
      9m 33s
    10. Viewing execution plans
      3m 37s
  8. 19m 36s
    1. Writing INSERT statements
      5m 47s
    2. Writing UPDATE statements
      4m 38s
    3. Writing DELETE statements
      2m 54s
    4. Using the OUTPUT clause to return inserted keys and GUIDs
      6m 17s
  9. 32m 52s
    1. Introduction to SQL functions
      6m 26s
    2. Using SQL configuration functions
      2m 14s
    3. Using string functions
      7m 26s
    4. Using date functions
      6m 27s
    5. Creating user-defined functions
      10m 19s
  10. 28m 46s
    1. Introduction to stored procedures
      4m 23s
    2. Creating stored procedures
      11m 23s
    3. Introducing transactions
      4m 23s
    4. Creating transactions
      8m 37s
  11. 16m 39s
    1. Understanding and creating indexes
      6m 32s
    2. Monitoring and rebuilding indexes
      6m 0s
    3. Monitoring database size and integrity
      4m 7s
  12. 11m 41s
    1. Creating backups
      4m 21s
    2. Creating differential backups and using backup compression
      3m 40s
    3. Restoring databases
      3m 40s
  13. 17m 40s
    1. Introduction to SQL Server security and permissions
      5m 54s
    2. Adding a Windows user to the database
      5m 7s
    3. Creating SQL Server logins and switching authentication modes
      6m 39s
  14. 36m 41s
    1. Introduction to SQL Server Reporting Services
      2m 52s
    2. Connecting to the Report Manager
      4m 29s
    3. Using Report Builder
      12m 4s
    4. Formatting values in reports
      4m 17s
    5. Adding indicators to reports
      5m 11s
    6. Adding charts to reports
      3m 54s
    7. Working with report security
      3m 54s
  15. 24m 41s
    1. Introduction to SQL Server Integration Services (SSIS)
      1m 57s
    2. Using Business Intelligence Development Studio (BIDS)
      6m 59s
    3. Creating and executing a simple SSIS package
      7m 35s
    4. Importing packages into SQL Server Management Studio
      3m 21s
    5. Scheduling jobs with SQL Server Agent
      4m 49s
  16. 31s
    1. Goodbye

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.

Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now "Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.

Mark all as unwatched Cancel


You have completed SQL Server 2008 Essential Training.

Return to your organization's learning portal to continue training, or close this page.

Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?


Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.