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.

Customer table 1

Python SQL Where Clause Example

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

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. Select Sorted Table Records
  4. Top 10 records
# 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 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 Clause wildcards Example

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

# 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 Clause Wildcards Example 3