Search code examples
sqldatabasedatabase-schema

Understanding Primary and Foreign Keys


I'm reading through a introductory PDF on SQL and came across the following: "A foreign key in a table is a column (or group of columns) which is a primary key in another table."

Would a table having Foreign Keys which form a group of columns just be directly related to multiple tables associated with these Foreign Keys?

Also, is it possible for a Table to have multiple Primary Keys? If so, what does this actually mean?

Thanks a lot


Solution

  • Would a table having Foreign Keys which form a group of columns just be directly related to multiple tables associated with these Foreign Keys?

    A table having foreign keys can be related (referenced) to multiple tables. Take this example,

    Table A
    --------
    Col1 FK references B.Col1
    Col2 FK references B.Col2
    Col3 FK references C.Col3
    ...
    
    Table B
    --------
    Col1 PK <---|
    Col2 PK <---| composite primary key
    
    Table C
    --------
    Col3 PK <--- single primary key
    

    In the above case, Table A has foreign keys (col1, Col2, Col3) that are primary keys for other tables (B and C). Note here, Table B's primary key is a composite primary key with 2 columns. Hence you need to refer both of them.

    is it possible for a Table to have multiple Primary Keys?

    No. But one PK may contain multiple columns.