SQL Multiple Foreign Keys as Primary Keys

Kairan picture Kairan · Apr 12, 2013 · Viewed 19.8k times · Source

If I declare the table below does it implicitly imply that both the foreign keys make a unique primary key or do I need to do something more to make both attributes as a primary key?

CREATE TABLE Report_has_Items
(
    ReportID int REFERENCES Report(ReportID) NOT NULL,
    ItemID int REFERENCES Item(ItemID) NOT NULL
)

Essentially both attributes which are foreign keys from other tables, together would form a unique key.

Answer

gtsouk picture gtsouk · Apr 12, 2013

No it doesn't. The above table has no primary key. If you want to use the fields as a primary key use:

CREATE TABLE Report_has_Items(
    ReportID int REFERENCES Report(ReportID) NOT NULL,
    ItemID int REFERENCES Item(ItemID) NOT NULL,
    PRIMARY KEY (ReportID, ItemID)
)

or something similar depending on your sql dilect.