Drop a Foreign Key

ALTER TABLE statement is used to drop a foreign key from a table once it has been created.

Syntax:

    ALTER TABLE table_name  
    
    DROP CONSTRAINT fk_name;

    Parameter explanation

    table_name: It specifies the name of the table where the foreign key has been created.

    fk_name: It specifies the name of the foreign key that you want to remove.

    Example:

    In the previous example we have seen how to create a foreign key.

    CREATE TABLE products  
    ( product_id INT PRIMARY KEY,  
      product_name VARCHAR(50) NOT NULL,  
      category VARCHAR(25)  
    );  
    CREATE TABLE inventory  
    ( inventory_id INT PRIMARY KEY,  
      product_id INT NOT NULL,  
      quantity INT,  
      min_level INT,  
      max_level INT,  
      CONSTRAINT fk_inv_product_id  
        FOREIGN KEY (product_id)  
        REFERENCES products (product_id)  
    );  

    Use the following command to drop the foreign key called fk_inv_product_id.

    ALTER TABLE [javatpoint].[dbo].[inventory]  
    
    DROP CONSTRAINT fk_inv_product_id;

    Output:

    SQL Drop a foreign 1

    Now the foreign key is dropped.


    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *