Python MSSQL: Using ORDER BY to Sort Query Results

Last updated 1 month ago | 94 views 75     5

Tags:- Python MSSQL

When working with databases, the order in which data is presented is often just as important as the data itself. SQL's ORDER BY clause allows you to sort your query results based on one or more columns. In this article, you’ll learn how to use ORDER BY in your Python programs to retrieve sorted results from Microsoft SQL Server (MSSQL) using the pyodbc library.


✅ Prerequisites

Software Required

  • Python 3.7 or newer

  • Microsoft SQL Server (any edition)

  • ODBC Driver 17/18 for SQL Server

Install the Required Python Package

pip install pyodbc

Example Table: Employees

We’ll use this table in our examples:

CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY,
    FirstName NVARCHAR(50),
    LastName NVARCHAR(50),
    Email NVARCHAR(100),
    Age INT,
    HireDate DATE,
    Salary DECIMAL(10, 2),
    IsActive BIT
);

Step 1: Establish a Connection

import pyodbc

conn = pyodbc.connect(
    "DRIVER={ODBC Driver 17 for SQL Server};"
    "SERVER=localhost;"
    "DATABASE=EmployeeDB;"
    "UID=your_username;"
    "PWD=your_password;"
)
cursor = conn.cursor()

Step 2: Basic Usage of ORDER BY

Example: Sort Employees by Last Name

cursor.execute("SELECT * FROM Employees ORDER BY LastName ASC")
rows = cursor.fetchall()

for row in rows:
    print(f"{row.FirstName} {row.LastName}")

ASC (ascending) is the default order.


Step 3: Descending Order

Example: Highest Salaries First

cursor.execute("SELECT FirstName, Salary FROM Employees ORDER BY Salary DESC")
rows = cursor.fetchall()

for row in rows:
    print(f"{row.FirstName} - ${row.Salary}")

Step 4: Sort by Multiple Columns

Example: Sort by IsActive, then by LastName

cursor.execute("SELECT FirstName, LastName, IsActive FROM Employees ORDER BY IsActive DESC, LastName ASC")
rows = cursor.fetchall()

for row in rows:
    status = "Active" if row.IsActive else "Inactive"
    print(f"{row.FirstName} {row.LastName} - {status}")

This groups active employees first and sorts each group alphabetically by last name.


Step 5: Dynamic Sorting with Parameters

Python doesn’t support parameterizing column names (only values), so you must sanitize user input manually when building dynamic ORDER BY clauses.

def get_sorted_employees(order_by_column="LastName", descending=False):
    allowed_columns = ["FirstName", "LastName", "Age", "Salary", "HireDate"]
    if order_by_column not in allowed_columns:
        raise ValueError("Invalid column for sorting.")

    direction = "DESC" if descending else "ASC"
    query = f"SELECT * FROM Employees ORDER BY {order_by_column} {direction}"
    
    cursor.execute(query)
    return cursor.fetchall()

for row in get_sorted_employees("Salary", descending=True):
    print(f"{row.FirstName} {row.LastName} - ${row.Salary}")

Full Working Example

import pyodbc

def fetch_employees_sorted_by_salary():
    try:
        conn = pyodbc.connect(
            "DRIVER={ODBC Driver 17 for SQL Server};"
            "SERVER=localhost;"
            "DATABASE=EmployeeDB;"
            "UID=your_username;"
            "PWD=your_password;"
        )
        cursor = conn.cursor()
        query = """
        SELECT EmployeeID, FirstName, LastName, Salary 
        FROM Employees 
        WHERE IsActive = 1
        ORDER BY Salary DESC
        """
        cursor.execute(query)
        for row in cursor.fetchall():
            print(f"{row.EmployeeID}: {row.FirstName} {row.LastName} - ${row.Salary}")
    except pyodbc.Error as e:
        print("Database error:", e)
    finally:
        cursor.close()
        conn.close()

fetch_employees_sorted_by_salary()

Tips for Using ORDER BY

Tip Why It Matters
Use DESC for rankings Show top results first (e.g., top salaries)
Combine with WHERE Filter and sort results efficiently
Index your sort columns Improve performance for large datasets
Limit user-controlled sorting Prevent SQL injection from dynamic queries

⚠️ Common Pitfalls

Problem Cause Solution
"Invalid column name" Typo in the column name Check spelling and case
SQL injection risk Unsanitized ORDER BY input Whitelist allowed columns explicitly
Unexpected order Sorting on a string column with mixed case Use COLLATE or normalize text
Slow performance Sorting large tables without indexing Add an index on sort column(s) if needed

Conclusion

The ORDER BY clause is essential for presenting data in a logical and useful format. With Python and MSSQL, you can easily sort data on any column, whether it’s alphabetically, numerically, or by date. For best results, combine sorting with filtering (WHERE) and always protect your dynamic queries with validation.