Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime error when using N-1 in limit clause of select query when N=0

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (
    SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT N-1,1
);
END

this query gives exception when M=0 as it becomes -1 however when I write it like

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
DECLARE M INT;
SET M=N-1;
  RETURN (
    SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT M,1
);
END

Please explain the difference between the two statements. When I set M= N-1 , m will also be negative when N=0 it gives following exception

Line 6: SyntaxError: near '-1,1
);
END'
like image 609
Amey jain Avatar asked Jun 08 '15 06:06

Amey jain


Video Answer


3 Answers

I'm not sure if this helps. But this looks like a problem from Leet Code (https://leetcode.com/problems/nth-highest-salary). I ran the below and it worked for me.

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
DECLARE M INT;
SET M=N-1;
RETURN (
   select distinct
       Salary
   from 
       Employee
   Order by 1 desc
   limit M, 1

   );
   END

And here's the submission result: enter image description here

Hope this helps!

like image 95
George Hayward Avatar answered Oct 27 '22 08:10

George Hayward


Don't forget to group the salaries.

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  set N = N - 1;
  RETURN (
      select salary from Employee group by salary order by salary desc limit 1 offset N
  );
END

So if you have two salaries of 100 and you are looking for 2nd highest, the answer should be NULL.

like image 26
oneekz Avatar answered Oct 27 '22 10:10

oneekz


I'm arriving late on this, but I struggled with this problem too. Spent hours debugging this. You could always check for this condition in the where clause. Check the query below.

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
DECLARE M INT;
SET M = -1;
 RETURN (
    select distinct salary from employee where M > 0 order by salary desc limit M,1
 );
END

The parameters in limit are confusing as well. In some cases offset is not supported. There's a simple example for this.

limit a,b;

We can read the above as

start from a and stop after b number of entries.

Cheers!

like image 20
sameera sy Avatar answered Oct 27 '22 09:10

sameera sy