title: SQL Server why am I getting error for creating foreign key constraint for no matching key in referenced table?
body: <p>I get this error from SQL Server:</p>
  <blockquote>
  <p>Msg 1776, Level 16, State 0, Line 64<br />
  There are no primary or candidate keys in the referenced table 'Orders' that match the referencing column list in the foreign key 'FK_Cart_Orders'.</p>
  </blockquote>
  <p>However, the <code>OrderID</code> column is in the <code>Orders</code> table, so I cannot understand why the error says there is no matching keys in the <code>Orders</code> table. I am obviously doing something wrong but do not know what it is.</p>
  <p>My code is fairly short and is:</p>
  <pre><code>CREATE DATABASE TestMattressSite
  GO
  
  USE TestMattressSite
  GO
  
  CREATE TABLE Mattresses 
  (
      MattressID INT IDENTITY NOT NULL,
  )
  GO
  
  CREATE TABLE Customers 
  (
      CustomerID INT IDENTITY NOT NULL,
  )
  GO
  
  CREATE TABLE Orders 
  (
      OrderID BIGINT IDENTITY NOT NULL,
      CustomerID INT NOT NULL,
  )
  
  CREATE TABLE Cart 
  (
      OrderID BIGINT NOT NULL,
      MattressID INT NOT NULL,
      CustomerID INT NOT NULL
  )
  GO
  
  ALTER TABLE Mattresses 
      ADD CONSTRAINT PK_Mattresses PRIMARY KEY (MattressID)
  GO
  
  ALTER TABLE Customers 
      ADD CONSTRAINT PK_Customers PRIMARY KEY (CustomerID)
  GO
  
  ALTER TABLE Orders 
      ADD CONSTRAINT PK_Orders PRIMARY KEY (OrderID, CustomerID)
  GO
  
  ALTER TABLE Cart 
      ADD CONSTRAINT PK_Cart PRIMARY KEY (OrderID, MattressID)
  GO
  
  ALTER TABLE Orders 
      ADD CONSTRAINT FK_Orders_Customers 
          FOREIGN KEY (CustomerID) REFERENCES Customers (CustomerID)
  GO
  
  ALTER TABLE Cart 
      ADD CONSTRAINT FK_Cart_Mattresses 
              FOREIGN KEY (MattressID) REFERENCES Mattresses (MattressID),
          CONSTRAINT FK_Cart_Orders 
              FOREIGN KEY (OrderID) REFERENCES Orders (OrderID),
          CONSTRAINT FK_Cart_Customers 
              FOREIGN KEY (CustomerID) REFERENCES Customers (CustomerID)
  GO
  </code></pre>
  <p>Can someone please take a look and point out my error?</p>