Skip to content
Advertisement

SQL – WHERE NOT EXISTS [closed]

I have a table with employees ID NAME SALARY

and I am getting the employee with the most salary with this SQL statement:

SELECT *
FROM Emplyees eOut
WHERE NOT EXISTS (SELECT * 
                  FROM Emplyees eIn 
                  WHERE eIn.Salary > eOut.Salary)

as I know the outer statement will be executed only if the inner one is true, so why this gives a result? I do not understand why there is only one result for this, how is this processed and why NOT and > is important for that?

Advertisement

Answer

The expression:

NOT EXISTS (SELECT * FROM Emplyees eIn WHERE eIn.Salary > eOut.Salary)

is a Boolean expression with possible values true or false.
It gets the value false when the inner query returns (at least) 1 row and true if the inner query returns no rows.

Your assumption:

the outer statement will be executed only if the inner one is true

as it is phrased is wrong.

The statement:

SELECT * FROM Emplyees eOut

will be executed and return all the rows of the table Emplyees and for each of these rows the WHERE clause will evaluate its condition to true or false.
So for every row of the table the condition NOT EXISTS ... will decide if that row will be in the final results or not.

To understand why NOT and > is important in this case, think of the query like this:

Select every employee for whom does not exist another employee with greater salary.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement