I have the following schema:
Emp(eid int, ename varchar(50), salary float, email varchar(80))
Works(eid int, did int, pct_time float)
Dept(did int, budget float, managerid int)
eid is for employee id.
did is for department id.
I’ve bolded primary keys.
managerid is a foreign key, as well as eid and did in Works.
Now, I’d like to add a “manager complex” assertion that ensure a manager will always have a higher salary than any employee that he/she manages.
Here’s what I’ve been thinking:
CREATE ASSERTION managerComplex
CHECK
( NOT EXISTS (SELECT M.salary
FROM Dept D, Emp M
WHERE D.managerid = M.eid) <=
(SELECT E.salary
FROM Works W, Emp E
WHERE W.eid = E.eid) AND
D.did = W.did);
Is this even close to right?
Also, maybe I should have just made a couple CHECKs instead of an insertion?
I feel like multiple CHECKs is sloppier but would probably be easier to get right.
EDIT: The main reason I am asking is because I don’t know if I’m correctly understanding NOT EXISTS
For
NOT EXISTS ( SELECT ...)to be true, theSELECT ...must return no results.You want to create a
SELECTstatement that will return any employee with a salary higher than the manager listed for the department(s) they work for. See if you can write that query, and then place it inside theNOT EXISTSI’m not entirely sure what you wrote is even valid SQL, but it’s certainly not what you want. I have a potential answer for you, but as this was marked homework, I’d like to attempt to prod you in the right direction before providing a complete answer.
As OP said the homework has been turned in…
My
NOT EXISTShas a query inside of it, that will return results if there are any employee salaries higher than their respective manager’s salary. I look at all employees who work for a department, and only pull them into the result set if their salary is higher than the manager for that department’s salary.I’m not even sure your SQL is valid, as you have a
(SELECT ...) <= (SELECT ...) AND .... Comparing result sets with a<=doesn’t make any sense to me. It’s possible that’s just SQL I’ve never used, but… I’ve never used it.