My issue
Practice - Multiple table udpate
We have an employees table with columns emp_id, emp_name, department and salary.
We also have a department_salary table with columns department and avg_salary.
Task
Write a PLSQL query for a trigger to update the ‘department_salary’ table with average salary for each department whenever insert or update queries are run on employee table.
Update the trigger update_department_salary given in the IDE to get the following output.
Expected output
DEPARTMENT AVG_SALARY
HR 56667
Operations 56000
My code
CREATE OR REPLACE TRIGGER update_department_salary
AFTER INSERT OR UPDATE ON employees
FOR EACH ROW
DECLARE
v_avg_salary NUMBER;
BEGIN
-- Calculate the average salary for each department and update the department_salary table
FOR dept_rec IN (SELECT DISTINCT department FROM employees) LOOP
-- Calculate the average salary for the department
SELECT AVG(salary)
INTO v_avg_salary
FROM employees
WHERE department = dept_rec.department;
-- Update the department_salary table with the calculated average salary
MERGE INTO department_salary ds
USING (SELECT dept_rec.department AS department FROM dual) d
ON (ds.department = d.department)
WHEN MATCHED THEN
UPDATE SET ds.avg_salary = v_avg_salary
WHEN NOT MATCHED THEN
INSERT (department, avg_salary) VALUES (dept_rec.department, v_avg_salary);
END LOOP;
END;
/
SELECT * FROM department_salary;
Learning course: Database management systems
Problem Link: Practice - Multiple table udpate in Database management systems