I suppose you are trying to order the salesmen by their sales success and find the (2nd) top. Then update that guy's salary by 12%.
I think the error is in line 3:
Update salespersons set salespersons.salary = salespersons.salary * 1.12
where salespersons.empid =
(SELECT employeeid --- change this
...
But there are other issues, too, and the query can (and should) be further simplified by removing one nesting level and (as @Mat pointed out) the redundant ROWNUM=2
and adding NULLS LAST
in the ordering to avoid placing nulls first. I think this (the nulls first or last) was the reason that no rows were updated in the first place:
Update salespersons set salary = salary * 1.12
where empid =
(SELECT employeeid
FROM (SELECT s.empid employeeid,
s.ename employeename,
SUM(i.price * oi.qty) - s.salary Topprofit
FROM salespersons s
LEFT JOIN orders o ON s.empid = o.empid
LEFT JOIN orderitems oi ON o.orderid = oi.orderid
LEFT JOIN inventory i ON oi.partid = i.partid
GROUP BY s.empid, s.ename, s.salary
ORDER BY Topprofit DESC NULLS LAST) --added NULLS LAST
WHERE ROWNUM = 2 and Topprofit is not null) ;
and using window functions:
UPDATE salespersons
SET salary = salary * 1.12
WHERE empid =
(SELECT employeeid
FROM (SELECT s.empid employeeid,
SUM(i.price * oi.qty) - s.salary AS Topprofit,
ROW_NUMBER() OVER (ORDER BY SUM(i.price * oi.qty) - s.salary DESC NULLS LAST)
AS Rn
FROM salespersons s
LEFT JOIN orders o ON s.empid = o.empid
LEFT JOIN orderitems oi ON o.orderid = oi.orderid
LEFT JOIN inventory i ON oi.partid = i.partid
GROUP BY s.empid, s.salary) t
WHERE Rn = 2 AND Topprofit IS NOT NULL) ;
You could also write the update like this:
UPDATE
(SELECT s.empid,
s.salary,
ROW_NUMBER() OVER (ORDER BY SUM(i.price * oi.qty) - s.salary DESC) AS Rn
FROM salespersons s
LEFT JOIN orders o ON s.empid = o.empid
LEFT JOIN orderitems oi ON o.orderid = oi.orderid
LEFT JOIN inventory i ON oi.partid = i.partid
GROUP BY s.empid, s.salary
HAVING (SUM(i.price * oi.qty) - s.salary) IS NOT NULL) t
SET salary = salary * 1.12
WHERE Rn = 2 ;