Search code examples
sqlsql-serverforeign-keyscreate-table

Add a foreign key when creating a new table


I'm trying to create a new table (Customer) and I'm trying to add the foreign key ZipCode, but its definitely not working I tried looking for possible solutions but I couldn't make it work with what I got. Any help is appreciated, thanks!

CREATE TABLE Zip_Code (
    ZipCode varchar(10) Not null,
    City varchar(20),
    StateCode varchar(2)
); 

ALTER TABLE Zip_Code
ADD Primary Key (ZipCode);

CREATE TABLE Customer (
    CustomerID INT Primary Key,
    CustomerName varchar(30),
    Address varchar(30),
    FOREIGN KEY (ZipCode) REFERENCES Zip_Code(ZipCode),
    CreditLimit money,
    Balance money,
);

Solution

  • The problem is not the primary key definition. The problem is customer. In order to declare a column as a foreign key, you have to define the column first:

    CREATE TABLE Customer (
        CustomerID INT Primary Key,
        CustomerName varchar(30),
        Address varchar(30),
        ZipCode varchar(10),
        FOREIGN KEY (ZipCode) REFERENCES Zip_Code(ZipCode),
        CreditLimit money,
        Balance money,
    );
    

    Here is a db<>fiddle.