Insert into tables with primary and foreign key at same time - sql

Very new to SQL and have spent a day on this already.
Here are my two tables:
Centre(cid, name, location, nurse_supervisor)
Nurse(nid, name, centre_id, certificate)
I have a big problem. The (nurse_supervisor) in Centre is a foreign key to Nurse (nid).
The (centre_id) in Nurse is a foreign key to (Centre cid).
I can't figure out how to populate these tables. I have tried:
INSERT ALL, which produces "A foreign key value has no matching primary key value"
I have tried removing the foreign key constraints and adding them after populating the tables but when I do that it says I can't add a constraint to tables with preexisting data.
I tried removing NOT NULL - but realized that was silly as the constraints will be enforced anyways.
Everything I look through says populate the parent table first and then the child, but these tables are linked to each other.
I am using SQL developer.

This is a poor schema design, but one way to get around it would be to:
Make both centre_id and nurse_supervisor columns NULL in the two table definitions
Insert all rows into both tables, but with NULL for those two columns
Update centre_id to the correct value for each row in the Nurse table
Update nurse_supervisor to the correct value for each row in the Centre table

Related

Why am I getting an Integrity Constraint (parent key not found) when the parent key exists

I have a parent record in my people table, but when trying to insert a matching record in my employee table, I get a integrity constraint error. Can anyone explain what is wrong?
Ah! Based on your comment:
I've added a pic of the foreign keys, personID is present is both the employee table and customer table and references the people table
it seems that you're mistaken.
Oracle doesn't check whether constraints exist, but whether data (that support those constraints) exist. In other words, first you have to insert a row into a parent table, and then into its child table (whose values "reference" primary key values in the parent table).
The way you posted it, you're inserting into child with no parent.
From the provided images, I can only guess that you are trying to insert a record into "Employee" table with "PersonId" that does not exist in the parent table "People"
If that is not the case, are you able to show us the whole table design including foreign keys?

A table that does not have a primary key and has only one foreign key, can the foreign key be duplicated?

Assuming that the EMP_SALARY_INFO table does not have any other relations apart from the EMPLOYEE table.
My question is there is no primary key for the EMP_SALARY_INFO table. There is only one foreign key. When I create entity instances for the EMP_SALARY_INFO table, my foreign key i.e., EMP_ID repeats. Is this valid or does it violate any relational database rule? If this repetition is a violation, would I have to create a unique id (primary key) for the EMP_SALARY_INFO table?
That is perfectly OK. I would call out that in your example there is a possibility of having duplicate date ranges for the same employee. For example, if a mistake is made during data entry you may have two different pay rates for the same date range. Now, this may be a valid scenario in your case, however if it’s not then consider creating a unique constraint on Emp_id, from_date and till_date.
Foreign key of a particular table is a primary key of the table its referring to. Hence, in your case above as long as you have data in your empid of employee and same data if referred from emp_salary_info wont cause any sort of problem even if it repeats in the emp_salary_info table as its not repeating in the table its referring to i.e. Employee

Is it correct to have a table in SQL with just foreign key columns?

Is it correct to have a table in SQL with just foreign key columns? All columns are foreign keys, except the primary key ID.
Here is the scenario in my mind. I wanted to be sure first and then implemented it.
I have three tables => Personnel, Position, Place. Personnel table has general information of employees, Position table has different job positions and tasks in a company, Place table has info about different places in the city. So, an Agent is one of the personnel with one of the job tasks who should go to do the task in one of the places. Agents could change every week, select between personnel and give them almost randomly tasks and places.
I'll give you an example where it is perfectly correct and desired:
when you have many to many relationship, say Table1 and Table2 the best practice states that you should have table, eg. Table1Table2 with just two columns: Table1Id and Table2Id, both foreign keys to respective tables and together they make primary key.
Having said that, it is perfectly correct, as long as it satisfies your design.
To say anything more, you should share your database schema.
you should add a foreign key on the child table referencing the parent table so it is correct that all fields be foreign key but you have to have primary key on that table.

One Primary Key Value in many tables

This may seem like a simple question, but I am stumped:
I have created a database about cars (in Oracle SQL developer). I have amongst other tables a table called: Manufacturer and a table called Parentcompany.
Since some manufacturers are owned by bigger corporations, I will also show them in my database.
The parentcompany table is the "parent table" and the Manufacturer table the "child table".
for both I have created columns, each having their own Primary Key.
For some reason, when I inserted the values for my columns, I was able to use the same value for the primary key of Manufacturer and Parentcompany
The column: ManufacturerID is primary Key of Manufacturer. The value for this is: 'MBE'
The column: ParentcompanyID is primary key of Parentcompany. The value for this is 'MBE'
Both have the same value. Do I have a problem with the thinking logic?
Or do I just not understand how primary keys work?
Does a primary key only need to be unique in a table, and not the database?
I would appreciate it if someone shed light on the situation.
A primary key is unique for each table.
Have a look at this tutorial: SQL - Primary key
A primary key is a field in a table which uniquely identifies each
row/record in a database table. Primary keys must contain unique
values. A primary key column cannot have NULL values.
A table can have only one primary key, which may consist of single or
multiple fields. When multiple fields are used as a primary key, they
are called a composite key.
If a table has a primary key defined on any field(s), then you cannot
have two records having the same value of that field(s).
Primary key is table-unique. You can use same value of PI for every separate table in DB. Actually that often happens as PI often incremental number representing ID of a row: 1,2,3,4...
For your case more common implementation would be to have hierarchical table called Company, which would have fields: company_name and parent_company_name. In case company has a parent, in field parent_company_name it would have some value from field company_name.
There are several reasons why the same value in two different PKs might work out with no problems. In your case, it seems to flow naturally from the semantics of the data.
A row in the Manufacturers table and a row in the ParentCompany table both appear to refer to the same thing, namely a company. In that case, giving a company the same id in both tables is not only possible, but actually useful. It represents a 1 to 1 correspondence between manufacturers and parent companies without adding extra columns to serve as FKs.
Thanks for the quick answers!
I think I know what to do now. I will create a general company table, in which all companies will be stored. Then I will create, as I go along specific company tables like Manufacturer and parent company that reference a certain company in the company table.
To clarify, the only column I would put into the sub-company tables is a column with a foreign key referencing a column of the company table, yes?
For the primary key, I was just confused, because I hear so much about the key needing to be unique, and can't have the same value as another. So then this condition only goes for tables, not the whole database. Thanks for the clarification!

ON UPDATE CASCADE with two columns in a single table in SQL Server [duplicate]

I have a database table called Lesson:
columns: [LessonID, LessonNumber, Description] ...plus some other columns
I have another table called Lesson_ScoreBasedSelection:
columns: [LessonID,NextLessonID_1,NextLessonID_2,NextLessonID_3]
When a lesson is completed, its LessonID is looked up in the Lesson_ScoreBasedSelection table to get the three possible next lessons, each of which are associated with a particular range of scores. If the score was 0-33, the LessonID stored in NextLessonID_1 would be used. If the score was 34-66, the LessonID stored in NextLessonID_2 would be used, and so on.
I want to constrain all the columns in the Lesson_ScoreBasedSelection table with foreign keys referencing the LessonID column in the lesson table, since every value in the Lesson_ScoreBasedSelection table must have an entry in the LessonID column of the Lesson table. I also want cascade updates turned on, so that if a LessonID changes in the Lesson table, all references to it in the Lesson_ScoreBasedSelection table get updated.
This particular cascade update seems like a very straightforward, one-way update, but when I try to apply a foreign key constraint to each field in the Lesson_ScoreBasedSelection table referencing the LessonID field in the Lesson table, I get the error:
Introducing FOREIGN KEY constraint 'c_name' on table 'Lesson_ScoreBasedSelection' may cause cycles or multiple cascade paths.
Can anyone explain why I'm getting this error or how I can achieve the constraints and cascading updating I described?
You can't have more than one cascading RI link to a single table in any given linked table. Microsoft explains this:
You receive this error message because
in SQL Server, a table cannot appear
more than one time in a list of all
the cascading referential actions that
are started by either a DELETE or an
UPDATE statement. For example, the
tree of cascading referential actions
must only have one path to a
particular table on the cascading
referential actions tree.
Given the SQL Server constraint on this, why don't you solve this problem by creating a table with SelectionID (PK), LessonID, Next_LessonID, QualifyingScore as the columns. Use a constraint to ensure LessonID and QualifyingScore are unique.
In the QualifyingScore column, I'd use a tinyint, and make it 0, 1, or 2. That, or you could do a QualifyingMinScore and QualifyingMaxScore column so you could say,
SELECT * FROM NextLesson
WHERE LessonID = #MyLesson
AND QualifyingMinScore <= #MyScore
AND #MyScore <= QualifyingMaxScore
Cheers,
Eric