0

I have a table like this:

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

I am writing a function with mySQL to get the n th largest value in Salary. Here is the function:

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (
    # Write your MySQL query statement below.
    select DISTINCT Salary 
    FROM Employee 
    ORDER BY Salary  DESC
    LIMIT 1 offset (N - 1)
    #FETCH NEXT 1 ROWS ONLY
    
  );
END

But I got the an error near (N-1). enter image description here

if I change (N-1) to 1 :

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (
    # Write your MySQL query statement below.
    select DISTINCT Salary 
    FROM Employee 
    ORDER BY Salary  DESC
    LIMIT 1 offset 1
    #FETCH NEXT 1 ROWS ONLY
    
  );
END

It runs correctly. So the question is how to reference input in SQL function? It seems it can be directly called as an argument as we do in other languages.

3
  • 1
    I get the error is not a problem description. What is the error you're seeing? What is the exact error message you're seeing? Commented Sep 22, 2020 at 4:23
  • @KenWhite it seems to be a syntax error. It just says it's near (N-1). No other specific information...I am using the SQL panel on leetcode. Commented Sep 22, 2020 at 4:25
  • @KenWhite the error message has been attached. Any clues? Commented Sep 22, 2020 at 4:34

2 Answers 2

1

LIMIT argument cannot be a variable. Use prepared statement - in it the LIMIT parameter may be taken from a variable. But dynamic SQL is not allowed in the function - use stored procedure:

CREATE PROCEDURE getNthHighestSalary(N INT)
BEGIN
    SET @sql := 'SELECT DISTINCT Salary 
                 INTO @output
                 FROM Employee 
                 ORDER BY Salary  DESC
                 LIMIT 1 OFFSET ?';
    PREPARE stmt FROM @sql;
    SET @output := N-1;
    EXECUTE stmt USING @output;
    DROP PREPARE stmt;
    SELECT @output;
END

fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, unfortunately, I am working on the leetcode problem, which requires me to write a function...But thanks anyway!
1

It seems I need to declare and set a variable before reference it in SQL query:

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
DECLARE M INT;
SET M=N-1;
  RETURN (
    # Write your MySQL query statement below.
    select DISTINCT Salary 
    FROM Employee 
    ORDER BY Salary  DESC
    LIMIT 1 OFFSET M
    #FETCH NEXT 1 ROWS ONLY 
  );
END

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.