CREATE FUNCTION get_nth (x int)
RETURNS int DETERMINISTIC
RETURN
SELECT MIN(m.salary)
FROM
(SELECT *
FROM salaries
ORDER BY salary DESC
LIMIT x) AS m;
I'm trying to fetch an nth salary from the table, that's why I have written this function, but it shows an error and I can't figure out why:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select min(m.salary) from (select * from salaries order by salary desc limit x) a' at line 3
This subquery is working fine as individual query.
CodePudding user response:
when using a subquery as a value in an expression, you need to enclose it in parentheses:
return (select min(m.salary) from (select * from salaries order by salary desc limit x)as m);