Tuesday, June 14, 2011

Interview Question: Database Query: Find nth maximum salaried employee.

This question was asked to me in an screening process of a product based company.

Oracle database has employee table having EMPLOYEE_ID and SALARY as columns. Identify all the employee who get 3rd best salary in the company.

My instant answer was as follows:

SELECT * FROM EMPLOYEE WHERE ROW_NUMBER = 3 ORDER BY SALARY DESC

There was instant reaction, this query is wrong. Yes, it is. It will give me the 3rd most earning employee of the company but it will give me the THIRD BEST salary of the company.

So I modified my query a little bit and answered as follows:

SELECT * FROM EMPLOYEE WHERE SALARY = (SELECT DISTINCT(SALARY FROM EMPLOYEE WHERE ROW_NUMBER = 3 ORDER BY SALARY DESC) )


This query will work fine on oracle database but will not run on any other database. Interviewer was right. Now I did not know the way to figure out the third best salary. I did some Google search and found following options.

SELECT * FROM (SELECT EMPLOYEE_ID, SALARY, RANK() OVER (ORDER BY SALARY DESC) RANKSAL FROM EMPLOYEE) WHERE RANKSAL = 3;


SELECT * FROM EMPLOYEE E WHERE 3=(SELECT COUNT(DISTINCT SALARY) FROM EMPLOYEE WHERE E.SALARY<= SALARY);

SELECT LEVEL,MAX(SALARY) FROM EMPLOYEE WHERE LEVEL =3 CONNECT BY PRIOR SALARY > SALARY GROUP BY LEVEL;


So there are few ways to to figure out the third best salary.

Now during interview this question can be twisted in the following manner.

  • Find the 3rd Minimum Salary.
  • Find 10th Maximum/Minimum Salary.
  • Find nth Maximum/Minimum salary of the Employee.
  • Find all employees having salary less than 3rd best salary.

Interview Questions - Puzzle

A person has 50 Red Balls, 50 Blue Balls and two empty Jars with the capacity of 200 balls. This guy has to distribute following balls in the jars available to him.

Distribute the balls such that probability of withdrawing the red ball is maximum.

Assumptions:

  • Person can pick any ball from any of the jars.
  • Jars need not to have number of balls.
  • It is not possible to place all the red balls on top of blue balls (This ordering will not work.) Person can shake the jars before withdrawing the ball.
In case of any doubts regarding the question, please comment.