SQLite Order By
Sort the Result
Use ORDER BY to sort the result. By default, it sorts from lowest to highest.
The examples on this page use this players table:
| name | score |
|---|---|
| Emil | 120 |
| Tobias | 95 |
| Linus | 150 |
| Lene | 80 |
To keep the examples short, they show only the code for the SELECT statement. Click "Try it Yourself" to see the complete code, which also creates the table and adds the rows.
Example
Sort the players by score:
cur.execute("""
SELECT * FROM players
ORDER BY score
""")
for row in cur.fetchall():
print(row)
Try it Yourself »
Sort Descending
Add DESC to sort from highest to lowest:
Example
Sort the players by score, highest first:
cur.execute("""
SELECT * FROM players
ORDER BY score DESC
""")
for row in cur.fetchall():
print(row)
Try it Yourself »
DESC is short for descending. The default order is ASC, ascending.
Sort Text
Text is sorted alphabetically:
Example
Sort the players by name:
cur.execute("""
SELECT * FROM players
ORDER BY name
""")
for row in cur.fetchall():
print(row)
Try it Yourself »
Limit the Result
Use LIMIT to get only some of the rows. Together with ORDER BY, you can make a top list:
Example
Get the 3 players with the highest scores:
cur.execute("""
SELECT * FROM players
ORDER BY score DESC
LIMIT 3
""")
for row in cur.fetchall():
print(row)
Try it Yourself »
Note: If you use WHERE too, write it before ORDER BY. LIMIT always comes last.
Print a High Score List
Here is the top list again, printed with a place number in front of each player:
Example
Print the top 3 players:
cur.execute("""
SELECT name, score FROM players
ORDER BY score DESC
LIMIT 3
""")
place = 1
for name, score in cur.fetchall():
print(place, name, score)
place += 1
Try it Yourself »