Python MySQL Order By
In this page:
cursor.execute("SELECT * FROM table_name ORDER BY column ASC") # or DESC
Sorting Ascending (the Default)
cursor.execute("SELECT * FROM customers ORDER BY name") returns customer rows sorted alphabetically by name from A to Z -- ascending order is the implicit default, so ASC does not need to be written explicitly, though it can be for clarity.
Example: Sorting Ascending (the Default)
from unittest.mock import MagicMock
conn = MagicMock()
cursor = conn.cursor()
cursor.execute("SELECT * FROM customers ORDER BY name") # ascending is the implicit default
print("Sorted A to Z by default")
Sorting Descending
Appending DESC after the column name in ORDER BY reverses the sort into descending order -- ORDER BY name DESC sorts alphabetically from Z to A, and ORDER BY price DESC would show the most expensive items first.
Example: Sorting Descending
from unittest.mock import MagicMock
conn = MagicMock()
cursor = conn.cursor()
cursor.execute("SELECT * FROM customers ORDER BY name DESC") # DESC reverses the sort order
print("Sorted Z to A")
Sorting by Multiple Columns
ORDER BY column1, column2 sorts primarily by column1, and for any rows that share the same column1 value, sorts those tied rows by column2 as a tie-breaker -- exactly like sorting a spreadsheet by one column, then a secondary column.
Example: Sorting by Multiple Columns
from unittest.mock import MagicMock
conn = MagicMock()
cursor = conn.cursor()
cursor.execute("SELECT * FROM customers ORDER BY city, name") # name breaks ties within the same city
print("Sorted by city, then name breaks ties")
Combining ORDER BY with WHERE
ORDER BY can be combined with a WHERE clause in the same query -- MySQL applies the WHERE filter first to narrow down which rows qualify, then sorts only that filtered subset, which is more efficient than filtering afterward in Python.
Example: Combining ORDER BY with WHERE
from unittest.mock import MagicMock
conn = MagicMock()
cursor = conn.cursor()
cursor.execute(
"SELECT * FROM customers WHERE city = %s ORDER BY name", # filtered first, then the subset is sorted
("Austin",),
)
print("Filtered first, then sorted")
Sorting by an Expression or Alias
ORDER BY is not limited to plain column names -- it can also sort by a computed expression, or by the alias given to a computed column in the SELECT list, letting you sort by values that do not exist as stored columns at all.
Example: Sorting by an Expression or Alias
from unittest.mock import MagicMock
conn = MagicMock()
cursor = conn.cursor()
cursor.execute(
"SELECT name, price * quantity AS total FROM orders ORDER BY total DESC" # sorts by the computed alias
)
print("Sorted by the computed 'total' alias")
- Assuming SELECT results come back in a specific, predictable order by default -- without an explicit ORDER BY, MySQL does not guarantee any particular row ordering.
- Forgetting the DESC keyword and expecting descending order, when ascending is the silent default for ORDER BY.
- Trying to sort by a column name that was not included in the accompanying SELECT column list when using SELECT with specific named columns rather than SELECT *.
- ORDER BY columnName sorts the query's results by that column, ascending by default.
- ORDER BY columnName DESC reverses the sort into descending order.
- Multiple columns can be listed in ORDER BY, sorting by the first column and using later columns as tie-breakers.
ORDER BY is standard SQL syntax, supported identically across every MySQL and mysql-connector-python version.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first:
- Python MySQL Get Started
- Python MySQL Create Database
- Python MySQL Create Table
- Python MySQL Insert Into Table
- Python MySQL Select From Table
- Python MySQL Select With a Filter
- Python MySQL Order By
- Python MySQL Delete Record
- Python MySQL Drop Table
- Python MySQL Update Table
- Python MySQL Limit
- Python MySQL Join