What is the difference b/w Primary Key and Unique Key

前端 未结 11 2008
孤城傲影
孤城傲影 2020-12-24 13:07

I tried to find it out in google but not satisfactory answer is given out there. Can anybody explain the solid difference.

actually if Primary key is used to sele

11条回答
  •  渐次进展
    2020-12-24 13:26

    A primary key does not allow nulls, a unique key will allow one null (on sql server and multiple nulls on Oracle) A table can only have one primary key but many unique keys

    use primary keys when you want to set up foreign key relationships

    Here is a small example with just one column in each table

    --primary key table
    CREATE TABLE PrimaryTest (id INT PRIMARY KEY NOT NULL)
    GO
    
    -- foreign key table
    CREATE TABLE ForeignTest (Pkid INT NOT NULL)
    GO
    
    
    --relationship
    ALTER TABLE dbo.ForeignTest ADD CONSTRAINT
        FK_ForeignTest_PrimaryTest FOREIGN KEY
        (
        Pkid
        ) REFERENCES dbo.PrimaryTest
        (
        id
        ) ON UPDATE  NO ACTION 
         ON DELETE  NO ACTION 
    
    GO
    

    insert a row in the primary key table

    insert PrimaryTest values(1)
    

    insert a row in the foreign key table with a value that exist in the primary key table

    insert ForeignTest values(1)
    

    Now this will fail because value 2 does not exist in the primary key table

    insert ForeignTest values(2)
    

    Msg 547, Level 16, State 0, Line 1 The INSERT statement conflicted with the FOREIGN KEY constraint "FK_ForeignTest_PrimaryTest". The conflict occurred in database "aspnetdb", table "dbo.PrimaryTest", column 'id'. The statement has been terminated.

提交回复
热议问题