Python SQLite: How to Use ORDER BY to Sort Query Results

Last updated 1 month ago | 97 views 75     5

Tags:- Python SQLite

When working with databases, it’s often important not just to retrieve data, but to control the order in which it's presented. The SQL ORDER BY clause allows you to sort query results in ascending or descending order based on one or more columns.

In this guide, you'll learn:

  • How to use ORDER BY in SQLite with Python

  • How to sort by one or multiple columns

  • How to sort in ascending and descending order

  • Common use cases and potential pitfalls


✅ Prerequisites

  • Python 3.x installed

  • SQLite database (example.db) with a Users table containing some data

Example table:

CREATE TABLE Users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT UNIQUE NOT NULL,
    age INTEGER
);

Sample data might look like:

(1, 'Alice', '[email protected]', 30)
(2, 'Bob', '[email protected]', 25)
(3, 'Charlie', '[email protected]', 35)

Step 1: Connect to the Database

import sqlite3

conn = sqlite3.connect("example.db")
cursor = conn.cursor()

Step 2: Use ORDER BY to Sort Results

Sort by a Single Column (Ascending by Default)

cursor.execute("SELECT * FROM Users ORDER BY age")
rows = cursor.fetchall()

for row in rows:
    print(row)

Explanation: Sorts all users from youngest to oldest (ASC is the default).


Sort by a Single Column in Descending Order

cursor.execute("SELECT * FROM Users ORDER BY age DESC")
rows = cursor.fetchall()

for row in rows:
    print(row)

Explanation: Adds DESC to reverse the order.


Step 3: Sort by Multiple Columns

cursor.execute("SELECT * FROM Users ORDER BY age ASC, name DESC")
rows = cursor.fetchall()

for row in rows:
    print(row)

Explanation:

  • Sorts first by age (ascending)

  • If ages are equal, sorts by name (descending)


Step 4: Apply ORDER BY with WHERE Clause

You can combine ORDER BY with WHERE to filter and sort at the same time:

cursor.execute("SELECT * FROM Users WHERE age >= 25 ORDER BY name ASC")
rows = cursor.fetchall()

for row in rows:
    print(row)

Full Example: ORDER BY with Python and SQLite

import sqlite3

# Connect to database
conn = sqlite3.connect("example.db")
cursor = conn.cursor()

# Sort users by age descending
cursor.execute("SELECT name, age FROM Users ORDER BY age DESC")
rows = cursor.fetchall()

print("Users sorted by age (descending):")
for name, age in rows:
    print(f"{name} - {age} years old")

# Sort users by name
cursor.execute("SELECT name, age FROM Users ORDER BY name ASC")
rows = cursor.fetchall()

print("\nUsers sorted by name (ascending):")
for name, age in rows:
    print(f"{name} - {age} years old")

conn.close()

Tips for Using ORDER BY in SQLite with Python

Tip Why It’s Useful
✅ Always specify ASC or DESC clearly Improves readability
✅ Use indexes on sorted columns for large datasets Speeds up queries
✅ Combine with WHERE to filter and sort together More powerful
✅ Use column names, not numbers, in ORDER BY More readable and maintainable

⚠️ Common Pitfalls

Problem Cause Solution
Wrong order Default is ascending Use DESC explicitly
Error when using column number SQLite does not always support it in Python Use column names
Performance lag on large data Sorting is slow on unindexed columns Use indexes or limit rows
Confusing multiple ORDER BYs Not sure of order Use parentheses or test in SQLite CLI

Best Practices

  • Use ORDER BY with LIMIT to get top N records (e.g., top 5 oldest users)

  • Use COLLATE NOCASE to sort text columns case-insensitively:

    SELECT * FROM Users ORDER BY name COLLATE NOCASE
    
  • Always test your sorting logic independently using a SQLite GUI or CLI


Conclusion

The ORDER BY clause in SQLite allows you to organize your query results effectively. With Python and the sqlite3 module, it’s easy to sort by one or more columns, control the order of display, and combine it with other SQL clauses like WHERE or LIMIT.

Sorting is essential when you're building data-driven apps like dashboards, reports, or user lists. Mastering ORDER BY ensures your data looks clean and professional every time.