22

I'm trying to retrieve some data from the database, which need to be the top 10 of the agents with the highest score.

My Query:

SELECT AgentScores.agentID, 
       AgentScores.totalScore, 
       Agents.firstname, 
       Agents.lastname 
FROM AgentScores 
INNER JOIN Agents ON AgentScores.AgentId=Agents.Agent_id 
ORDER BY AgentScores.totalScore DESC 
LIMIT 10

The inner joins are working. I've found the SELECT TOP 10 sql statement but.. I want the 10 agents with the highest score and not the first 10 id's. As you can see I'm ordering on the totalscore.

Anyone has a clue how to fix this?

Error: Array ( [0] => Array ( [0] => 42000 [SQLSTATE] => 42000 [1] => 102 [code] => 102 [2] => [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near 'LIMIT'. [message] => [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near 'LIMIT'. ) )

Thank you!

1
  • "I want the 10 agents with the highest score and not the first 10 id's" - That's what your ORDER BY clause is for. You're not sorting by ID values, so why would it limit based on those?
    – David
    Jul 29, 2015 at 15:20

2 Answers 2

43

You have to use TOP clause instead of LIMIT

SELECT TOP 10 AgentScores.agentID, AgentScores.totalScore, Agents.firstname, Agents.lastname FROM AgentScores INNER JOIN Agents ON AgentScores.AgentId=Agents.Agent_id ORDER BY AgentScores.totalScore DESC
1
  • 7
    but why is that so ?
    – Jitin
    Apr 23, 2021 at 9:04
14

In order to limit rows in MSSQL, you have to use SELECT TOP 10 .... instead of LIMIT 10 (limit is a MySQL clause, not MSSQL)

4
  • @drmavelous But.. doesn't it just grab the first 10 id's in the database? Like, what if I have 100 agents and id 87 has the highest score.. Doesn't it just only order the first 10 id's?
    – peer
    Jul 29, 2015 at 15:15
  • No, as it will read from the ORDER BY clause and select the top 10 matching that Jul 29, 2015 at 15:16
  • no, you keep the order by clause as is, so it will return the first 10 records based on the order specified in the order by clause. Jul 29, 2015 at 15:18
  • "In a SELECT statement, always use an ORDER BY clause with the TOP clause. This is the only way to predictably indicate which rows are affected by TOP." source
    – 1010
    Jul 30, 2015 at 3:25

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.