Python SQL Where Clause

In this chapter, we explain how to write a SQL Where in the Python Programming language. And how to filter the Table records in Python with an example. Before we get into the SQL Where example, let me show you the data.

Python SQL Where Example 1

Python SQL Where Clause Example 1

In this Python example, we show how to use the Where Clause to filter the Data or restrict the records based on condition.

TIP: Please refer to Connect Python to SQL Server article to understand the steps involved in establishing a connection.

# Python SQL Where Example
import pyodbc
WhereConn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=PRASAD;"
                      "Database=SQL Tutorial;"
                      "Trusted_Connection=yes;")

WhereCursor = WhereConn.cursor()
WhereCursor.execute('SELECT * FROM CustomerSale WHERE YearlyIncome >= 60000')

for row in WhereCursor:
    print('row = %r' % (row,))
Python SQL Where Example 2

The below Python program selects all the records from the Customer Sales table whose Yearly Income is greater than or equal to 60000.

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

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

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

Python SQL Where Example 2

In this Python example, we are using Wildcards to filter the data. The below Python program returns all the records from a table whose Occupation ends with l. 

# Python SQL Where Example
import pyodbc
WhereConn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=PRASAD;"
                      "Database=SQL Tutorial;"
                      "Trusted_Connection=yes;")

WhereCursor = WhereConn.cursor()
WhereCursor.execute("SELECT * FROM CustomerSale WHERE Occupation LIKE N'%l' ")

for row in WhereCursor:
    print('row = %r' % (row,))
Python SQL Where Example 3