Updating an attribute to a foreign key - sql

So I've currently got a database with a table named subject, within this is the name of the subject and the full name of the person responsible.
I've just added a new table with contact information, which has a primary key employee_id, and other attributes including employee_fn and employee_ln.
What I'm essentially trying to achieve, is to update the 'responsible' attribute from being the full name to being a foreign key referencing employee_id where the name corresponds accordingly.
I'm having trouble writing the SQL for this and honestly can't even work out how to do it manually nor with a query.
Any help is appreciated!
Thanks

From your question what i understand is you want to have responsible column as FK of Subject table and point it to the employee_id as FK ..right??
But that's not possible as FK needs to PK in other table. Employee_id will be an integer and will not be able to hold the full name.
Any sample data with expected output will help you out.
However if you have employee_id as a column in subject table then this update will work.
update subject s
set responsible = (
select employee_fn||employee_ln as fullname,employee_id
from
employee
) e
where e.employee_id = s.employee_id
your subject must have employee_id as fk and employee table as employee_id as PK for PK-FK relationship.

Related

SQL Query to get rows with keys that are primary keys in the same table that also point to other primary keys?

so I had this one SQL problem asked to me on a coding challenge and I initially understood it wrong. Basically given an Employee table, with a primary key being EmployeeID theres also a column named say ManagerID. That ManagerID references a primary key in the same Employee table. Let's say EmployeeID 1's Manager is EmployeeID 3 who has a manager with EmployeeID 4.
How would a query look like to list all the Employees next to their managers? I'm a novice when it comes to SQL but is there a way to do this with say a for/while loop since it's possible for a low level employee to link all the way up the chain of command many times?

update or delete on table "employee" violates foreign key constraint

I have an employee table with the following columns:
fname (varchar), lname (varchar), id (numeric)
id is the primary key.
There is a table name called works_on with columns
projectname (varchar), id (numeric)
Here, id is a foreign key that references the employee table.
When I was trying delete a row from the employee table like this:
delete from employee where id = 1
I get this error:
update or delete on table "employee" violates foreign key constraint "works_on_id_fkey" on table "works_on"`.
I am new to the database management system.
Any solution?
As employee is a foreign key in table works_on; the reason you are unable to delete employee ID 1 is because employee ID 1 exists on works_on (or perhaps other tables in which employee is a foreign key). The system is trying to maintain integrity of the database by preventing you from deleting an employee affiliated with works_on.
Say the system let you delete the employee record. Now when you look at the works_on table what would employee 1 relate to? You can no longer look up first/last names among other information. So the system is saying: If you want to delete the employee record, you must first remove/alter the foreign key associations to other system records; to ensure their continued integrity. If the system let you do this it would be called "Orphaning" a record. the parent record to which the child associates no longer exists.
To resolve a few options are:
Create a procedure that deletes employees but first checks any tables in which employee is a foreign key and ensures it's ok to delete those as well; and then deletes those records before deleting the employee record. (this can cause a massive daisy chain if those tables have PK's to which other tables are FK. But that's the nature of RDBMS.
Create a feature that lets you assign such records to employee 1's replacement or removes such records if no longer relevant.
enable ON DELETE CASCADE ON UPDATE CASCADE, which will automatically delete child records if parent record is deleted. (BE VERY CAREFUL AND CONSIDER how this impacts your system before enabling) Example: Docs
Don't delete the record, instead maintain a status field showing active/inactive and use it as a control mechanism to show or not show employees and their associated records.
There's several other options to consider as well; you must ask yourself, or the business for which this is being developed, what should happen to all those records in which employee 1 is a foreign key. Delete some/All, reassign some delete some? Prompt the user for how they want to handle each instance? Simply Inform the user they must first address the constraints found in (List all places this employee has a FK relationship?) and ensure they have a way to handle all those places... Lots of options.
You can not delete a row by that way. Because it has the constraint id in it (works_on_id_fkey). If you want to delete, you have to remove constraint from it.
alter table employee drop foreign key works_on_id_fkey

Create a table containing PK and FK

I am trying to explain what this table does, but unable to see what is happening here. Any suggestion?
CREATE TABLE EMP
(
ID INT NOT NULL PRIMARY KEY,
MGID INT REFERENCES EMP (ID),
NAME VARCHAR(30) NOT NULL
);
It's creating a table called EMP which describes employees. Each employee is identified by a surrogate ID number, has a NAME attribute, and a relationship with a manager identified by MGID.
This code creates a table that's called EMP, with a primary key column called ID of type int, a foreigen key referencing that column called MGID, and a string column called NAME.
Using a foriegn key to the same table enables you to create parent/child relationship for rows in that table.
For instance, if you have an employee that's called Raza, and his manager is calld Far, You will have a row for the manager and a row for Raza and the value of MGID in that row would point to the ID of Far
Assuming that you have some basic knowledge of DBMS, I think you stuck with 'REFERENCES' keyword.
It creates a Parent/Child relationship between ID and MGID.
As you know, the table is for Employee(as the name suggested 'Emp'), Manager is also an employee.
So,before referencing to any employee as a manager it must have entry in table as employee. To perform this kind of validations, 'REFERENCES' keyword can be used.
For example,
ID MGID NAME
1 null a
2 1 b
3 1 c
Above data is valid but,
ID MGID NAME
1 null a
2 3 b
3 1 c
Above data will violate the referential integrity constraints as any employee with ID 3 is not existed yet.
Hope it helps.

SQL: FOREIGN KEY prevents destruction of links between tables

Refer: w3schools-SQL
It states:
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. Can someone give an example of an action that foreign key would prevent ?
Thanks.
Lets say we have the two tables Employees and Departments. Each department has a unique number, and for each employee we list the number of the department that he or she works on. We have also declared this as a foreign key.
In that case the foreign key would prevent a number of actions:
Inserting a new employee who works on a department that doesn't exist
Deleting a department where there are employees who work
Updating an employee by changing the department he or she works on to a department that doesn't exist
Updating a department by changing its number, if there are employees who work on that department
Destroying the department table
All this is to ensure that when the database says that an employee works on a certain department, then that department will actually exist in the database.
Table Employee has its primary key set to empid.
Table Address references (foreign key constraint) empid in Table Employee
If you try deleting employee '1011' from Table Employee and that employee has a record in Table Address the delete will not go through because of the dependency. Unless you have cascading delete set up..
Table Users
ID UserName
1 msmucker0527
2 Jake
Table Email (Foreign Key: UserID = Users.ID)
UserID Email
1 msmucker0527#email.net
2 jake#email.net
You cannot add a record to the Email table with a UserID that does not exist in the Users Table. This way you don't have email addresses that are not "linked" to a User. You would also be prevented from deleting a user without first removing the email address so that it would not become stranded

How To Create a Complex Table in sqlServer?

Lets say I have a table called Employees , and each employee has a primarykey called (E_ID)
and I have another table called Positions , and each Position has a primarykey called (P_ID)
and I also have another table called offices , and each office has an ID called (O_ID)
Now I want to create a table that has three primaryKeys which are (E_ID) and (P_ID) and (O_ID) ...
ofcourse these three values must be withdrawl from the first three tables , but I just can't do it anyway ?
please help me because I neeeeeeed it badly
thanks verymuch
If it was me, I think I'd just add P_ID and O_ID to Employees. The same Position might be filled by multiple employees, and there might be multiple Employees at a given Office, but it's unlikely (without using Cloning technology) that the same Employee would need to be replicated multiple times - thus, just add P_ID and O_ID to Employee and I think you're good to go. Of course, you'll need foreign key constraints from Employee to Position (P_ID) and Office (O_ID).
EDIT: After some thought, and recalling that I've had jobs where I filled multiple positions (although at the same location), I suppose it's conceivable that a single person might have fill multiple positions which might be at different locations.
If you're really set on having a junction table between Employees, Positions, and Offices - OK, create a table called EmployeePositionOffice (or something like that) which contains the three columns E_ID, P_ID, and O_ID. The primary key should be (E_ID, P_ID, O_ID), and each field should be foreign-keyed to the related base table.
EDIT:
Not sure about the SQL Server syntax, but in Oracle the first would be something like:
ALTER TABLE EMPLOYEES
ADD (P_ID NUMBER REFERENCES POSITIONS(P_ID),
O_ID NUMBER REFERENCES OFFICES(O_ID));
while the second would be something like
CREATE TABLE EMPLOYEES_POSISTIONS_OFFICES
(E_ID NUMBER REFERENCES EMPLOYEES(E_ID),
P_ID NUMBER REFERENCES POSITIONS(P_ID),
O_ID NUMBER REFERENCES OFFICES(O_ID),
PRIMARY KEY (E_ID, P_ID, O_ID));
Share and enjoy.