Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is the first time I use SQL, and I have a problem with adding a foreign key to my table.

I have 2 tables: ORDER_T (referenced) and ORDER_ITEM (referencing)

create table ORDER_T(
Id int primary key, 
OrderDate date,
TotalAmount int
); 


create table ORDER_ITEM(
UnitPrice int,
Quantity int,
OrderID int,
ProductID int
);


This is my code to add a foreign key:

ALTER TABLE ORDER_ITEM
ADD FOREIGN KEY (OrderID) REFERENCES ORDER_T(Id);


But, it gives me this error:
Quote:
Error: near "FOREIGN": syntax error


Help?

What I have tried:

I tried to search online to figure out what I did wrong, or what is the meaning of the error, but to no avail.
Posted
Comments
0x01AA 22-Dec-23 8:07am    
I tried your statements with MS SQL. For me it works fine...

Create a foreign key in an existing table - Create Foreign Key Relationships - SQL Server | Microsoft Learn[^]
SQL
ALTER TABLE ORDER_ITEM
ADD CONSTRAINT FK_ORDER_ITEM_ORDER_T FOREIGN KEY (OrderID) REFERENCES ORDER_T(Id);
 
Share this answer
 
Comments
0x01AA 22-Dec-23 8:05am    
I tried OP's statements 1:1. For me everything works with them. Anyway a 5.
Rama2F 22-Dec-23 8:22am    
I'm sorry, but I'm having difficulty understanding your comment, since English is not my first language. Are you saying that when copying my code, it does NOT give you an error? If so, could you please provide me the name of the compiler / program you are using? Thank you.
0x01AA 22-Dec-23 8:26am    
You are correct. I copied your code and everything works fine, no error message.
I tried that with MSSQL Management Console. My server version is:
Microsoft SQL Server 2019 (RTM) - 15.0.2000.5 (X64)
Sep 24 2019 13:48:23
Copyright (C) 2019 Microsoft Corporation
Express Edition (64-bit) on Windows 10 Pro 10.0 <x64> (Build 19045: )
Rama2F 22-Dec-23 8:29am    
Thank you.
Rama2F 22-Dec-23 8:17am    
I tried it, but it gave me the following error message: Error: near "CONSTRAINT": syntax error
You need to do the following:
SQL
ALTER TABLE TABLE2 
ADD CONSTRAINT[symbol] 
FOREIGN KEY(column_name) 
REFERENCES TABLE1(column_name);

Thus, your case:
SQL
ALTER TABLE ORDER_ITEM 
ADD CONSTRAINT FK_ORDERS 
FOREIGN KEY(OrderID) 
REFERENCES ORDER_T(Id);

Refer: SQL - Foreign Key[^]
 
Share this answer
 
Comments
Rama2F 22-Dec-23 8:20am    
I tried it, but it gave me the following error message: Error: near "CONSTRAINT": syntax error
Sandeep Mewara 22-Dec-23 9:29am    
This works as is. Not sure what exactly you might be doing wrong post copy-pasting above.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900