0

There is a table Employee as below:

enter image description here

I need finds out employees who earn more than their managers and I figure out two methods:

  1. SELECT a.Name AS Employee FROM Employee a, Employee b WHERE a.Salary > b.Salary AND a.ManagerId = b.Id;
  2. SELECT a.Name AS Employee FROM Employee a INNER JOIN Employee b ON a.Salary > b.Salary AND a.ManagerId = b.Id;

Both of them work well and have close speed.

What's the difference between them? Thanks.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
Leonard Peng
  • 55
  • 1
  • 8
  • Borh queries are identical, but the first one uses the now deprecated pre ANSI-92 join sintax (I call it sintax rather than syntax, because many gurus on this site consider it a sin to put join conditions in the `WHERE` clause). – Tim Biegeleisen Aug 05 '16 at 03:57
  • But i think , both are correct but only for simple quires, For big queries Join will be better, Join not only uses for filter but also for joining to table in efficient way , But ' where ' only uses for filters. – Amitesh Kumar Aug 05 '16 at 04:00
  • They are same. However the most preferred Syntax is: SELECT staff.Name FROM Employee AS staff INNER JOIN Empolyee AS manager ON staff.ManagerId = manager.Id WHERE staff.Salary > manager.Salary – SIDU Aug 05 '16 at 04:01

1 Answers1

1

Those queries are equivalent. But you should use the join syntax instead of commas in the from clause. INNER JOIN ON vs WHERE clause

Here's an alternative option which might have a better performance using exists:

select e.Name AS Employee
from employee e
where exists (
   select 1
   from employee e2
   where e.managerid = e2.id and e.salary > e2.salary
)
Community
  • 1
  • 1
sgeddes
  • 62,311
  • 6
  • 61
  • 83