Python SQL Select Top

In this section, we explain to you how to write a SQL Select Top in the Python Programming language. Or how to write a SQL Server query to select the top 10 records in Python with an example.

Before we get into the SQL Select Top 10 example, let me show you the data that we use.

Source Table 1

Python SQL Select Top Example 1

In this Python example, we show how to use the Top Clause to select the first 10 records from a customer sales table.

TIP: Please refer to Connect to Server article to understand the steps involved in establishing a connection from Python. 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. Select Sorted Table Records
  4. Where Clause
import pyodbc
TopConn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=PRASAD;"
                      "Database=SQL Tutorial;"
                      "Trusted_Connection=yes;")

TopCursor = TopConn.cursor()
TopCursor.execute("SELECT TOP 10 * FROM CustomerSale ")

for row in TopCursor:
    print('row = %r' % (row,))
Python SQL Select Top Example 2

The below Python program selects the first 10 or top 10 records in a Customer Sales table.

TopCursor.execute("SELECT TOP 10 * FROM CustomerSale ")

Next, we used the For loop to iterate records present in the Top Cursor. Within the For Loop, we used the print statement to print records.

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

Python Select Top 10 records Example 2

In this example, we are using Order By Clause along with Top Clause. Below program sort data in Descending order using Sales, and then it selects the first 10 records from the sorted table. 

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

TopCursor = TopConn.cursor()
TopCursor.execute("SELECT TOP 10 * FROM CustomerSale ORDER BY Sales DESC")

for row in TopCursor:
    print('row = %r' % (row,))
Python SQL Select Top Example 3

Python SQL Select Top Example 3

In this Python example, we are using the Percent to select the top 40 percent records from a customer sales. 

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

TopCursor = TopConn.cursor()
TopCursor.execute("SELECT TOP 40 PERCENT * FROM CustomerSale ORDER BY Sales DESC")

for row in TopCursor:
    print('row = %r' % (row,))
Python SQL Select Top Example 4