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 Where example, please visit the Python Charts Data article to see the data we will use. Please visit the Python Programming tutorial to learn fundamentals.

Python SQL Where Clause Example

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

TIP: Please refer to the Connect Python to SQL Server article to understand the steps involved in establishing a connection. The following are a few of the operations we can do on Microsoft 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,))
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 Python 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,))

SQL Where Clause wildcards Example

In this example, we are using SQL LIKE Wildcards to filter the data. The program below 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,))
Where Clause Wildcards Example 3