Use ORDER BY with TOP to return the top x rows based on a column's value

suggest change

TOP is SQL Server syntax. In this example, ORDER BY decides both the sort and, together with TOP, which rows are returned.

Let’s say we want to return the top 5 highest reputation users from an unnamed popular Q&A site.

Without ORDER BY

TOP without ORDER BY does not define which rows come back. A result might look like the following, and another run can differ. Jeff Atwood’s reputation in this sample is 25784, and Joel Spolsky’s is 37628.

SELECT TOP 5 DisplayName, Reputation
FROM Users

returns…

DisplayName | Reputation |
—— | —— |
Community | 1 |
Geoff Dalgas | 12567 |
Jarrod Dixon | 11739 |
Jeff Atwood | 25784 |
Joel Spolsky | 37628 |

With ORDER BY

SELECT TOP 5 DisplayName, Reputation
FROM Users
ORDER BY Reputation DESC

The list below is a larger Users table, not the five-row sample above.

returns…

DisplayName | Reputation |
—— | —— |
JonSkeet | 865023 |
Darin Dimitrov | 661741 |
BalusC | 650237 |
Hans Passant | 625870 |
Marc Gravell | 601636 |

Remarks

Some versions of SQL (such as MySQL) use a LIMIT clause at the end of a SELECT, instead of TOP at the beginning, for example:

SELECT DisplayName, Reputation
FROM Users
ORDER BY Reputation DESC
LIMIT 5

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents