Reputation: 199
Can anyone help me answer why my query returns a syntax error? I'm working on the Hackerrank problem linked here.
Here's the code I wrote:
SELECT MAX(SELECT e1.salary * e1.months FROM Employee as e1) as max_tot_earnings, COUNT(e.employee_id)
FROM Employee as e
WHERE e.salary * e.months = max_tot_earnings
I get the following syntax error:
ERROR 1064 (42000) at line 1: 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 e1.salary * e1.months FROM Employee as e1) as max_tot_earnings, COUNT(e.e' at line 1
I know that the subquery doesn't have a syntax error. It runs just fine when run on its own. I was also able to work around the problem, so the purpose of this question is to try and figure out what's going on. I was able to solve the problem with the query shown below:
SELECT (SELECT e1.salary * e1.months as tot_earnings FROM Employee as e1 ORDER BY tot_earnings DESC LIMIT 1) as max_tot_earnings, COUNT(e.employee_id)
FROM Employee as e
GROUP BY e.salary, e.months
HAVING e.salary * e.months = max_tot_earnings
I found a few questions here that touch on using SELECT MAX(SELECT ...), but I didn't find answers for the two questions as phrased above. Questions one, two, and three.
In sum, I have two main questions:
Upvotes: 0
Views: 345
Reputation: 1269973
The correct syntax is:
SELECT (SELECT MAX(e1.salary * e1.months) FROM Employee as e1) as max_tot_earnings,
COUNT(e.employee_id)
FROM Employee as e
WHERE e.salary * e.months = max_tot_earnings;
Or more simply as:
SELECT (e.salary * e.months) as max_tot_earnings, COUNT(*)
FROM Employee
GROUP BY max_tot_earnings
ORDER BY max_tot_earnings DESC
LIMIT 1;
Your query doesn't work for the following reasons:
MAX( (SELECT . . . ) )
at least meets the parentheses requirements.MAX()
function takes an argument that is either a column reference or a constant or an expression that evaluates to a scalar. Your function call does not do that.MAX()
doesn't allow subqueries at all, even scalar subqueries.Upvotes: 1