Python SQL Order By

In this section, we explain to you how to write a SQL Order By in the Python Programming language. And how to sort the SQL Server Table records in Python with an example. 

Before we get into the Order By example, let me show you the data that we use.

Customer table 1

Python SQL Order By Example

In this Python example, we show how to use the Order By Clause to sort the Data in Ascending.

TIP: Please refer to Connect to Server article to understand the steps involved in establishing a connection. The following are a few of the operations we can do on SQL Server but are not limited to them.

  1. Create Database
  2. Select Records from Table
  3. Top 10 records
  4. Where Clause

Here, ASC is the keyword for the Ascending Order. By default, Order by clause, and sort data in ascending. So, it is optional to include the ASC keyword.

import pyodbc
dbConn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=PRASAD;"
                      "Database=SQL Tutorial;"
                      "Trusted_Connection=yes;")

OrderCursor = dbConn.cursor()
OrderCursor.execute('SELECT * FROM CustomerSale ORDER BY  YearlyIncome')

for row in OrderCursor:
    print('row = %r' % (row,))
Python SQL Order by Example 2

First, we selected data from the Customer Sales table present in Tutorial Database. This data is sorted by Yearly Income in Ascending.

OrderCursor.execute('SELECT * FROM CustomerSale ORDER BY YearlyIncome')

Next, we used the For loop to iterate each row present in the Order Cursor. Within the For Loop, we used the print statement to print rows in a table.

for row in OrderCursor: 
   print('row = %r' % (row,))

SQL Order By Descending Example

This Python SQL Server Order By example sorts the Customer table in descending using the Yearly Income column. 

import pyodbc
dbConn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=PRASAD;"
                      "Database=SQL Tutorial;"
                      "Trusted_Connection=yes;")

OrderCursor = dbConn.cursor()
OrderCursor.execute('SELECT * FROM CustomerSale ORDER BY YearlyIncome DESC')

for row in OrderCursor:
    print('row = %r' % (row,))
Descending Example 3