Python MSSQL: SELECT Data – Step-by-Step Guide with Code Examples

Last updated 1 month, 4 weeks ago | 147 views 75     5

Tags:- Python MSSQL

Once you’ve inserted data into your Microsoft SQL Server (MSSQL) database, the next step is retrieving it. Python, combined with the pyodbc library, makes it easy to execute SQL SELECT queries and fetch results for reporting, analytics, or application logic.

In this tutorial, you’ll learn how to retrieve data from MSSQL using Python, handle different result formats, and avoid common issues.


✅ Prerequisites

Ensure the following are set up before starting:

Required Software and Tools:

  • Python 3.7 or later

  • Microsoft SQL Server

  • ODBC Driver 17 or 18 for SQL Server

Install Required Python Package:

pip install pyodbc

You should also have a database and a table, such as the following:

CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY,
    FirstName NVARCHAR(50),
    LastName NVARCHAR(50),
    Email NVARCHAR(100),
    Age INT,
    HireDate DATE,
    Salary DECIMAL(10, 2),
    IsActive BIT
);

Step 1: Connect to MSSQL Database

SQL Server Authentication Example

import pyodbc

conn = pyodbc.connect(
    "DRIVER={ODBC Driver 17 for SQL Server};"
    "SERVER=localhost;"
    "DATABASE=EmployeeDB;"
    "UID=your_username;"
    "PWD=your_password;"
)
cursor = conn.cursor()

Windows Authentication Example

conn = pyodbc.connect(
    "DRIVER={ODBC Driver 17 for SQL Server};"
    "SERVER=localhost;"
    "DATABASE=EmployeeDB;"
    "Trusted_Connection=yes;"
)
cursor = conn.cursor()

Step 2: SELECT Data from a Table

Basic Query – Fetch All Records

cursor.execute("SELECT * FROM Employees")
rows = cursor.fetchall()

for row in rows:
    print(row)

Each row is a tuple containing column values in order.


Step 3: Fetching Results

fetchone() – Get a Single Row

cursor.execute("SELECT * FROM Employees")
row = cursor.fetchone()
print(row)

fetchall() – Get All Rows

cursor.execute("SELECT * FROM Employees")
rows = cursor.fetchall()
for row in rows:
    print(f"ID: {row.EmployeeID}, Name: {row.FirstName} {row.LastName}")

fetchmany(n) – Get N Rows

cursor.execute("SELECT * FROM Employees")
partial_rows = cursor.fetchmany(2)
for row in partial_rows:
    print(row)

Step 4: Select Specific Columns or Apply Conditions

Select Specific Columns

cursor.execute("SELECT FirstName, LastName FROM Employees")
for row in cursor.fetchall():
    print(f"{row.FirstName} {row.LastName}")

Apply WHERE Clause

cursor.execute("SELECT * FROM Employees WHERE IsActive = 1")
for row in cursor.fetchall():
    print(row)

Step 5: Use Parameterized Queries (Recommended)

Prevent SQL injection and handle dynamic values safely.

is_active = 1
cursor.execute("SELECT * FROM Employees WHERE IsActive = ?", (is_active,))
rows = cursor.fetchall()
for row in rows:
    print(row)

Bonus: Convert Results to Dictionary or Pandas DataFrame

Convert Results to Dictionary

columns = [column[0] for column in cursor.description]
data = [dict(zip(columns, row)) for row in cursor.fetchall()]
print(data)

Convert Results to Pandas DataFrame

import pandas as pd

df = pd.read_sql("SELECT * FROM Employees", conn)
print(df.head())

Full Working Example

import pyodbc

try:
    conn = pyodbc.connect(
        "DRIVER={ODBC Driver 17 for SQL Server};"
        "SERVER=localhost;"
        "DATABASE=EmployeeDB;"
        "UID=your_username;"
        "PWD=your_password;"
    )
    cursor = conn.cursor()

    # Execute SELECT query
    cursor.execute("SELECT EmployeeID, FirstName, LastName, Salary FROM Employees WHERE IsActive = ?", (1,))
    
    # Fetch results
    rows = cursor.fetchall()
    for row in rows:
        print(f"{row.EmployeeID}: {row.FirstName} {row.LastName}, Salary: {row.Salary}")

except pyodbc.Error as e:
    print("Database error:", e)

finally:
    cursor.close()
    conn.close()

Tips for Using SELECT with Python and MSSQL

Tip Description
Use parameterized queries Prevent SQL injection and make your code safer
Use fetchall() for small datasets For large datasets, use fetchmany() in chunks
Convert to Pandas for analysis Ideal for data analysis and exporting to Excel/CSV
Close cursor and connection Always release database resources after operations

⚠️ Common Pitfalls

Problem Cause Solution
No results returned WHERE clause filters too strictly Test your query in SQL Server Management Studio
Column access errors Typing column names incorrectly Use cursor.description to inspect actual names
Memory issues with large result sets Using fetchall() on millions of rows Use fetchmany() in batches instead

Conclusion

Retrieving data from Microsoft SQL Server with Python is simple and powerful using pyodbc. Whether you're building dashboards, automating reports, or powering a backend, you can use SELECT queries to efficiently fetch the data you need.

With proper use of parameterized queries and data structures like dictionaries or Pandas, your Python-MSSQL integration will be fast, secure, and scalable.