Create a table in SQL where the Composite Primary Key is also a Foreign Key - sql

I need to create a table called LFM_Enroll in SQL that has a composite primary key of Student_ID and Section_Number. Student_ID is also a foreign key, it references Student_ID in the LFM_Student table and Section_Number is also a foreign key, it references Section_Number in the LFM_Section table. How do I write the constraints and foreign keys? I've attached an image of the tables and below is what I have done so far. After the LFM_Enroll table is created I need to update one row. I tried doing so but kept getting the below error.
: Error starting at line : 173 in command -
UPDATE LFM_Enroll
SET Student_ID = 1234567,
Section_Number = 01234
WHERE Student_ID = 900000 AND Section_Number = 4138
Error report -
ORA-02291: integrity constraint (SYSTEM.FK_LFM_ENROLL_SECTION_NUMBER) violated - parent key not found.
Tables Thanks in advance for all your help.
CREATE TABLE LFM_Enroll (
Student_ID char(7),
Section_Number char(4),
constraint PK_LFM_Enroll Primary Key (Student_ID,Section_Number),
constraint FK_LFM_Enroll_Student_ID
Foreign Key (Student_ID,Section_Number) references LFM_Student (Student_ID),
constraint FK_LFM_Enroll_Section_Number
Foreign Key (Student_ID,Section_Number) references LFM_Section (Section_Number)
);

Your foreign key constraints are not right. You are trying to map two columns {Student_ID,Section_Number} to a single column LFM_Student.Student_ID.
The number of columns in the principal key must match the number of columns in the foreign key. In other words, the key LFM_Student is one column (Student_ID), so the foreign key also needs to be a single matching column - in this case LFM_Enroll.Student_ID. Correct DDL would be:
constraint FK_LFM_Enroll_Student_ID
Foreign Key (Student_ID) references LFM_Student (Student_ID),
constraint FK_LFM_Enroll_Section_Number
Foreign Key (Section_Number) references LFM_Section (Section_Number)
I'm not quite sure why your RDBMS is allowing what you have, but it may be using the first column and simply ignoring the second. In which case FK_LFM_Enroll_Section_Number is creating a foreign key LFM_Enroll.Student_ID => LFM_Section.Section_Number.

The error indicates that the values with which you are trying to update the two columns may not exist in Student and / or Sections tables i.e. 1234567 doesn't exists in the student table and / or 01234 doesn't exist in your section table . You should try inserting new rows or updating existing ones with the new values you are trying to update your foreign keys with.
[Edit: For defining constraints refer lc.'s post]

Related

Create table with foreign key to an other table created below in sql file

My problem is that i have two tables with each table having a foreign key to the other table.
Each time , i execute the SQL file containing the creation of the two tables, it gives me an error that he doesn't find the other table. I'm working with sqlplus to execute the sql file.
Here's an example of SQL file i tried with :
create table A(
Age number(3),
name number(3) constraint A_FK references B(name))
/
create table B(
Age number(3) constraint B_FK references A(Age),
name number(3))
And even if i reverse the order, it gives the same error.
Thanks for help.
This is a problem of cycles in foreign keys. One method is to add all foreign keys after table creation (as I think the other answers propose).
You can also just do that for the first table:
create table A (
Age number(3) primary key,
name number(3)
);
create table B (
name number(3) primary key,
Age number(3),
constraint B_FK foreign key (age) references A(Age)
);
alter table B add constraint A_FK foreign key (name) references B(name);
Here is a db<>fiddle.
Notes:
Foreign keys should reference primary keys, so I added that declaration as well.
I recommend making the primary key the first column in the table.
You can also define the constraint inline for one of the tables (i.e. age number(3) constraint b_fk references a(age)).
The table column(s) that is referred by a foreign key must exist at the time when the constraint is created. Since you have some kind of cyclic reference between the tables, you need to do this in three steps:
first create one table without the foreign key
create the second table (with its foreign key)
finally add the foreign key to the first table with an alter table statement
You also need the referred column to have a unique or primary key constraint set up, otherwise you would get error ORA-02270: no matching unique or primary key for this column-list.
create table A(
age number(3) primary key,
name number(3)
);
create table B(
age number(3) constraint B_FK references A(Age),
name number(3) primary key
);
alter table A add constraint A_FK foreign key (name) references B(name);
Demo on DB Fiddle
Side note: I am quite suspicious about your sample structure, but this could be because your oversimplified it in the question.
It fails because the reference table doesn't exist yet.
Create the tables without the key first. Then drop one and recreated it with the reference. Then drop the 2nd and recreate it with the reference.
Create table first and then ADD the CONSTRAINT
ALTER TABLE A
ADD FOREIGN KEY (name) REFERENCES B(name);
ALTER TABLE B
ADD FOREIGN KEY (age) REFERENCES A(age);

How to have more than one foreign key?

I'm having trouble adding more than 1 foreign key to my tables, I am getting the error:
"Error report -
ORA-02270: no matching unique or primary key for this column-list
02270. 00000 - "no matching unique or primary key for this column-list"
*Cause: A REFERENCES clause in a CREATE/ALTER TABLE statement
gives a column-list for which there is no matching unique or primary
key constraint in the referenced table.
*Action: Find the correct column names using the ALL_CONS_COLUMNS
catalog view"
I tried making the table without the third foreign key and it worked so I think its something to do with the last key but not really sure. (I put spaces in between the SQL to make it easier to read.)
CREATE TABLE ORDER(
ORDERID CHAR(4) NOT NULL,
HOUSETYPE CHAR(2),
CHAIR CHAR(2),
PERSON CHAR(2),
PAYDAY DATE,
MENUPRICE NUMBER(4,2),
CONSTRAINT CONFERENCESESSION_PK PRIMARY KEY(ORDERID),
CONSTRAINT CONFERENCESESSION_FK1 FOREIGN KEY(HOUSETYPE) REFERENCES
HOUSE(HOUSETYPE),
CONSTRAINT CONFERENCESESSION_FK2 FOREIGN KEY(PAYDAY) REFERENCES PERSON(PAYDAY),
CONSTRAINT CONFERENCESESSION_FK3 FOREIGN KEY(MENUPRICE) REFERENCES
MENU(MENUPRICE)
);
A foreign key must reference another table primary key, my guess is that some of you foreign keys don't reference the primary key of the other table.
A FOREIGN KEY is a key used to link two tables together.
A FOREIGN KEY is a field (or collection of fields) in one table that
refers to the PRIMARY KEY in another table.
The table containing the foreign key is called the child table, and
the table containing the candidate key is called the referenced or
parent table.
https://www.w3schools.com/sql/sql_foreignkey.asp
A foreign key must reference another table primary key so make sure you are doing that with the right name of the primary key. For example:
CONSTRAINT CONFERENCESESSION_FK2 FOREIGN KEY(PAYDAY) REFERENCES PERSON(PAYDAY)
Make sure that in table PERSON you have PRIMARY KEY with name PAYDAY.

How to add foreign key to an existing column in SQL Server 2012

I am trying to add foreign key to my existing column using below query
ALTER TABLE Sub_Category_Master
ADD FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
but I'm getting an error
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__Sub_Categ__Categ__5812160E". The conflict occurred in database "shaadikarbefikar_new", table "shaadikarbefikar.Category_Master", column 'Category_ID'.
Well, the error clearly tells you that Category_ID in your Sub_Category_Master table contains some values that are not present in Category_Master (column Category_ID). But that's exactly the point of having a foreign key constraint - making sure your child table (Sub_Category_Master) only uses defined values from its parent table.
Therefore, you must fix those "voodoo" values first, before you're able to establish this foreign key relationship. I would also strongly recommend to explicitly name that constraint yourself, to avoid those system-generated, but not really very useful constraint names like FK__Sub_Categ__Categ__5812160E:
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FK_SubCategoryMaster_CategoryMaster
FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FKSub_Category_Master_Category_ID FOREIGN KEY (Category_ID)
REFERENCES Category_Master(Category_ID);
CREATE TABLE Orders
(
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

Is it possible to reference a primary key in one table as a foreign key constraint across more than 2 tables?

I am currently making a database back end system on an airport, using sql through the phpmyadmin server. The criteria is not meant to be perfect but one of the ideas behind the queries is to imagine that either a customer or flight dispatch officer might be looking at the tables. I was wondering if it was possible to reference a primary key as a foreign key across 2 or more tables. In the example below, I want to reference the model number as a foreign key in the bottom 2 tables. I have ensured that the type and character count are the same.
CREATE TABLE Aircraft_Model
(Model_Number varchar (12) NOT NULL,
seat_capacity int (3),
CONSTRAINT pk7 primary key (Model_Number));
CREATE TABLE Licence_type
(Rank varchar (25) NOT NULL,
Model_Number varchar (12),
CONSTRAINT pk9 primary key (Rank));
CREATE TABLE Aircraft
(Aircraft_ID varchar (4) NOT NULL,
Model_Number varchar(12),
airport_base text(13),
CONSTRAINT pk1 PRIMARY KEY (Aircraft_ID));
Is this possible? I only want the database to be able to perform about 12-15 simple queries.
Would the syntax of adding a foreign key be something like this?
ALTER TABLE Aircraft
ADD CONSTRAINT fk1 FOREIGN KEY(Model_Number)
REFERENCES Aircraft_Model
Does the same foreign key being referenced from a separate table such as Licence_type need a separate constraint to be added or can it be added from the same one with the same fk1 number?
I was wondering if it was possible to reference a primary key as a
foreign key across 2 or more tables.
If you mean, "Can two or more tables have foreign keys that reference the same column?", then, yes, you can do that. This seems to be what you mean, but it's not what most people mean when they talk about "a foreign key across 2 or more tables".
Declare two different, separate constraints.
ALTER TABLE Aircraft
ADD CONSTRAINT fk1 FOREIGN KEY(Model_Number)
REFERENCES Aircraft_Model (Model_Number);
ALTER TABLE License_Type
ADD CONSTRAINT fk2 FOREIGN KEY(Model_Number)
REFERENCES Aircraft_Model (Model_Number);

Foreign Key Problem

I have two tables:
DeptMast
EmpMast
Both of tables have a column called DeptName and I have primary keys on DeptName in both tables.
Now when I go to create a foreign key on column DeptName of EmpMast, SQL Server gives me this error:
There are no primary or candidate keys in the referenced table
'DEPTMAST' that match the referencing column list in the foreign key
'FK_Key'.
If I create unique index on deptmast.Deptname then I don't get any error. Why does this happen?
You marked it as a primary key, so it cannot be a foreign key as well. A foreign key can appear multiple times in the table, while a primary key cannot.