Write a postgre SQL statement to insert rows into the table employees in which a set of columns department_id and manager_id contains a unique value and that combined value must have existed into the table departments.
INSERT INTO departments VALUES(60,'SALES',201,89);
INSERT INTO departments VALUES(61,'ACCOUNTS',201,89);
INSERT INTO departments VALUES(80,'FINANCE',211,90);
Here is the command to see the list of inserted rows :
INSERT INTO employees VALUES(510,'Alex','Hanes','CLERK',18000,201,60);
INSERT INTO employees VALUES(511,'Kim','Leon','CLERK',18000,211,80);
Here is the command to see the list of inserted rows :
postgres=# SELECT * FROM employees;
employee_id | first_name | last_name | job_id | salary | manager_id | department_id
-------------+------------+-----------+--------+----------+------------+---------------
510 | Alex | Hanes | CLERK | 18000.00 | 201 | 60
511 | Kim | Leon | CLERK | 18000.00 | 211 | 80
(2 rows)
The value against department_id and manager_id combination (60,201) and (80,211) are unique in the departmentis(parent) table so, there is no problem arise to insert the rows in the child table employees.
Now insert another row in the employees table :
INSERT INTO employees VALUES(512,'Kim','Leon','CLERK',18000,80,211);
Now see the output :
postgres=# INSERT INTO employees VALUES(512,'Kim','Leon','CLERK',18000,80,211);
ERROR: insert or update on table "employees" violates foreign key constraint "employees_department_id_fkey"
DETAIL: Key (department_id, manager_id)=(211, 80) is not present in table "departments".
Here is the code to create a sample table departments :
Now input three rows into the table departments:
Here is the command to see the list of inserted rows :
Here is another table employees :
Now insert the rows in the table employees.
Here is the command to see the list of inserted rows :
The value against department_id and manager_id combination (60,201) and (80,211) are unique in the departmentis(parent) table so, there is no problem arise to insert the rows in the child table employees.
Now insert another row in the employees table :
Now see the output :
need an explanation for this answer? contact us directly to get an explanation for this answer