Q
Problem solve Get help with specific problems with your technologies, process and projects.

Foreign keys in a composite primary key

Is it possible to use one of the attributes of a composite primary key as a foreign key?

Is it possible to use one of the attributes of a composite primary key as a foreign key?

Yes, this is quite common and perfectly valid.

The best example comes from the classic many-to-many relationship. Here is a simple diagram illustrating the relationship or association or linking table (it has other names, too, but these are the most common) between Categories and Articles. Note that there are two one-to-many relationships for the Article_Categories table. This means that the foreign keys for these relationships are in the Article_Categories table.

+--------------+          +--------------+
|  Categories  |          |   Articles   |
+--------------+          +--------------+
        |                        |
     1  |                        |  1
        +--------+      +--------+
                 |      |
              M  |      | M
                 V      V
         +----------------------+
         |  Article_Categories  |
         +----------------------+

These tables might be defined as follows:

create table Categories
( catid    integer      not null primary key
, category varchar(37)  not null
);
create table Articles
( artid    integer      not null primary key 
, title    varchar(255) not null
, body     text         not null
, artdate  datetime     not null
);
create table Article_Categories
( artid integer not null 
, catid integer not null 
, primary key ( artid, catid )
, foreign key ( artid ) 
     references Articles ( artid )
, foreign key ( catid ) 
     references Categories ( catid )
);

The primary key of Article_Categories is a composite key. Each of its components is a foreign key to its respective table.

By the way, notice that there is no autonumber in the Article_Categories table. Using an autonumber PK in a relationship or association table is one of the more common errors made by novices.

This was last published in October 2006

Dig Deeper on Oracle and SQL

PRO+

Content

Find more PRO+ content and other member only offers, here.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide.com

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close