NULL-waarden verwerken

SQL NULL staat voor ontbrekende of onbekende gegevens. De mssql-python-driver koppelt SQL NULL aan PythonNone. Het onderscheid is belangrijk omdat NULL niets betekent, inclusief zichzelf. In SQL, wordt NULL = NULL geëvalueerd als NULL (onbekend), niet true, dus gebruik IS NULL in query's en is None in Python.

NULL-waarden ontvangen

NULL in ophaalresultaten

De driver retourneert NULL-waarden van SQL Server als PythonNone:

import mssql_python

conn = mssql_python.connect(connection_string)
cursor = conn.cursor()

cursor.execute(
    "SELECT TOP 1 FirstName, MiddleName, LastName "
    "FROM Person.Person WHERE MiddleName IS NULL"
)
row = cursor.fetchone()

print(row.FirstName)   # First name value
print(row.MiddleName)  # None (NULL in database)
print(row.LastName)    # Last name value

Controleer op NULL-waarden

Controleer of een waarde None is met behulp van de operator is tijdens het doorlopen van de resultaten:

cursor.execute(
    "SELECT FirstName, MiddleName, LastName FROM Person.Person WHERE BusinessEntityID <= 10"
)

for row in cursor:
    if row.MiddleName is None:
        print(f"{row.FirstName} {row.LastName}: No middle name")
    else:
        print(f"{row.FirstName} {row.MiddleName} {row.LastName}")

Gebruik is None in plaats van == None

Gebruik het altijd is None voor NULL-checks. De is operator controleert identiteit (of de waarde letterlijk Noneis), terwijl == aanroepen __eq__ en onverwachte resultaten kunnen geven met aangepaste objecten:

# Correct
if row.MiddleName is None:
    full_name = f"{row.FirstName} {row.LastName}"

# Avoid (works but not idiomatic)
if row.MiddleName == None:
    full_name = f"{row.FirstName} {row.LastName}"

Stuur NULL-waarden

Voeg NULL in met None

Als u NULL-waarden wilt invoegen, geef None op:

cursor.execute(
    "CREATE TABLE #NullInsertDemo "
    "(Name NVARCHAR(50), Email NVARCHAR(100), Phone NVARCHAR(20))"
)
cursor.execute(
    "INSERT INTO #NullInsertDemo (Name, Email, Phone) "
    "VALUES (%(name)s, %(email)s, %(phone)s)",
    {"name": "Alice", "email": None, "phone": "555-1234"}
)
conn.commit()

Update naar NULL

Stel een kolom in op NULL door de volgende parameters in te geven None :

cursor.execute(
    "CREATE TABLE #UpdateDemo (ID INT, Email NVARCHAR(100))"
)
cursor.execute("INSERT INTO #UpdateDemo VALUES (100, 'old@example.com')")
cursor.execute(
    "UPDATE #UpdateDemo SET Email = %(email)s WHERE ID = %(id)s",
    {"email": None, "id": 100}
)
conn.commit()

Voorwaardelijke NULL-behandeling

Definieer functies die optionele parameters omgaan door ze in te stellen op None wanneer niet beschikbaar:

def update_record(cursor, record_id: int, name: str, email: str | None = None):
    """Update record, setting email to NULL if not provided."""
    cursor.execute(
        "UPDATE #Records SET Name = %(name)s, Email = %(email)s "
        "WHERE ID = %(id)s",
        {"name": name, "email": email, "id": record_id}
    )

NULL in WHERE-clausules

IS NULL in queries

Gebruik IS NULL in SQL voor NULL-vergelijkingen:

# Find people without a middle name
cursor.execute("SELECT FirstName FROM Person.Person WHERE MiddleName IS NULL")

# Find people with a middle name
cursor.execute("SELECT FirstName FROM Person.Person WHERE MiddleName IS NOT NULL")

Dynamische NULL-afhandeling

Wanneer een parameter mogelijk NULL is, gebruik dan conditionele logica om de juiste query te construeren:

def find_people(cursor, middle_name: str | None = None):
    """Find people, optionally filtering by middle name."""
    if middle_name is None:
        # Find people with NULL middle name
        cursor.execute("SELECT * FROM Person.Person WHERE MiddleName IS NULL")
    else:
        # Find people with specific middle name
        cursor.execute(
            "SELECT * FROM Person.Person WHERE MiddleName = %(middle_name)s",
            {"middle_name": middle_name},
        )
    return cursor.fetchall()

COALESCE voor NULL-substitutie

Gebruik COALESCE om standaardwaarden te vervangen door NULL op SQL-niveau. COALESCEis efficiënter dan controleren None in Python omdat de substitutie op de server plaatsvindt, waardoor de hoeveelheid conditionele logica in je applicatie afneemt:

cursor.execute("""
    SELECT 
        FirstName,
        COALESCE(MiddleName, '(none)') AS MiddleName,
        COALESCE(Suffix, 'N/A') AS Suffix
    FROM Person.Person
    WHERE BusinessEntityID <= 10
""")

for row in cursor:
    # MiddleName and Suffix will never be None
    print(f"{row.FirstName}: {row.MiddleName}, {row.Suffix}")

NULL-veilige operaties

Standaardwaarden in Python

cursor.execute("SELECT TOP 10 Name, Color FROM Production.Product")

for row in cursor:
    # Use or to provide default
    color = row.Color or "No color"
    print(f"{row.Name}: {color}")

NULL-waarden opmaken

def format_address(row):
    """Format address handling NULL components."""
    parts = [
        row.AddressLine1,
        row.AddressLine2,
        row.City,
        row.PostalCode,
    ]
    # Filter out None values
    return ", ".join(str(p) for p in parts if p is not None)

cursor.execute(
    "SELECT TOP 10 AddressLine1, AddressLine2, City, PostalCode "
    "FROM Person.Address"
)
for row in cursor:
    print(format_address(row))

NULL in aggregaties

SQL-aggregatefuncties behandelen NULL-waarden anders dan je zou verwachten. COUNT(column) telt alleen niet-NULL-waarden, terwijl COUNT(*) alle rijen telt. AVG, SUM, , MINen MAX negeren allemaal NULL-waarden. Als elke waarde in de kolom NULL is, geven deze functies NULL (niet nul) terug.

# COUNT excludes NULL values
cursor.execute("SELECT COUNT(Color) FROM Production.Product")  # Counts non-NULL colors
color_count = cursor.fetchval()

# COUNT(*) includes all rows
cursor.execute("SELECT COUNT(*) FROM Production.Product")  # Counts all products
total_count = cursor.fetchval()

# AVG ignores NULL
cursor.execute("SELECT AVG(Weight) FROM Production.Product")  # Average of non-NULL weights
average_weight = cursor.fetchval()

NULL in gegevenstypen

NULL numerieke waarden

from decimal import Decimal

cursor.execute("SELECT ListPrice FROM Production.Product WHERE ProductID = 1")
row = cursor.fetchone()

# Check before arithmetic
if row.ListPrice is not None:
    tax = row.ListPrice * Decimal("0.08")
    total = row.ListPrice + tax
else:
    total = Decimal("0")

NULL-datumwaarden

Controleer of een datumkolom staat None voordat je deze gebruikt bij vergelijkingen of berekeningen:

from datetime import date

cursor.execute("SELECT Name, SellEndDate FROM Production.Product WHERE ProductID <= 10")

for row in cursor:
    if row.SellEndDate is None:
        print(f"{row.Name}: Currently selling")
    else:
        print(f"{row.Name}: Discontinued on {row.SellEndDate}")

NULL-stringwaarden

Behandel kolommen met NULL-strings door te controleren op None vóór het samenvoegen:

cursor.execute(
    "SELECT TOP 10 FirstName, MiddleName, LastName FROM Person.Person"
)

for row in cursor:
    # Build full name, handling NULL middle name
    if row.MiddleName:
        full_name = f"{row.FirstName} {row.MiddleName} {row.LastName}"
    else:
        full_name = f"{row.FirstName} {row.LastName}"
    print(full_name)

Bulkbewerkingen met NULL

executemany met NULL-waarden

Wanneer u executemany() gebruikt, geef None door in woordenboeken voor kolommen die NULL moeten worden:

users = [
    {"name": "Alice", "title": "Ms.", "suffix": "Jr."},
    {"name": "Bob", "title": None, "suffix": "Sr."},  # NULL title
    {"name": "Carol", "title": "Dr.", "suffix": None},  # NULL suffix
]

cursor.executemany(
    "SELECT FirstName FROM Person.Person WHERE FirstName = %(name)s",
    users
)

Bulkkopiëren met NULL

Bulk-kopieeroperaties behouden NULL-waarden uit je datastructuren:

cursor = conn.cursor()

cursor.execute("CREATE TABLE ##NullDemo (Name NVARCHAR(50), Email NVARCHAR(100), Phone NVARCHAR(20))")
conn.commit()

data = [
    ("Alice", "alice@example.com", "555-0001"),
    ("Bob", None, "555-0002"),      # NULL Email
    ("Carol", "carol@example.com", None),  # NULL Phone
]

result = cursor.bulkcopy("##NullDemo", data)
conn.commit()
print(f"Copied {result['rows_copied']} rows")

Algemene patronen

Optionele veldverwerking

Gebruik typehints om te verduidelijken welke velden NULL kunnen zijn bij het toewijzen van rijen aan dataklassen:

from dataclasses import dataclass
from typing import Optional

@dataclass
class PersonRecord:
    business_entity_id: int
    first_name: str
    middle_name: Optional[str] = None
    suffix: Optional[str] = None

def fetch_person(cursor, person_id: int) -> Optional[PersonRecord]:
    cursor.execute(
        "SELECT BusinessEntityID, FirstName, MiddleName, Suffix "
        "FROM Person.Person WHERE BusinessEntityID = %(id)s",
        {"id": person_id},
    )
    row = cursor.fetchone()
    if row is None:
        return None
    return PersonRecord(
        business_entity_id=row.BusinessEntityID,
        first_name=row.FirstName,
        middle_name=row.MiddleName,  # Will be None if NULL
        suffix=row.Suffix,           # Will be None if NULL
    )

JSON-serialisatie met NULL

Python-waarden None worden automatisch omgezet naar JSON null wanneer je de json module gebruikt:

import json

cursor.execute(
    "SELECT TOP 5 BusinessEntityID, FirstName, MiddleName FROM Person.Person"
)
rows = cursor.fetchall()

# Convert to JSON-serializable list
people = []
for row in rows:
    people.append({
        "id": row.BusinessEntityID,
        "name": row.FirstName,
        "middle_name": row.MiddleName,  # None becomes null in JSON
    })

json_output = json.dumps(people, indent=2)
print(json_output)
# [
#   {"id": 1, "name": "Ken", "middle_name": "J"},
#   {"id": 3, "name": "Roberto", "middle_name": null}
# ]

Woordenboek met NULL-filtering

Kies ervoor om NULL-waarden uit te sluiten bij het omzetten van rijen naar woordenboeken:

def row_to_dict(row, cursor) -> dict:
    """Convert row to dict, optionally excluding NULL values."""
    columns = [col[0] for col in cursor.description]
    return {col: val for col, val in zip(columns, row) if val is not None}

cursor.execute("SELECT * FROM Person.Person WHERE BusinessEntityID = 1")
row = cursor.fetchone()
person_dict = row_to_dict(row, cursor)
# Only includes non-NULL columns

NULL in DataFrames

Als je werkt met pandas of Polars DataFrames, moet je extra goed letten op null-waarden omdat deze bibliotheken hun eigen sentinelwaarden gebruiken.

pandas NaN en NaT

pandas gebruikt NaN (Not a Number) voor ontbrekende numerieke en stringwaarden, en NaT (Not a Time) voor ontbrekende datum-tijdwaarden. Geen van beide waarden is hetzelfde als in PythonNone:

import pandas as pd
import numpy as np

# When reading SQL results into pandas, NULL becomes NaN or NaT
cursor.execute("SELECT Name, Weight, SellEndDate FROM Production.Product")
table = cursor.arrow()
df = table.to_pandas()

# Check for missing values (covers NaN, NaT, and None)
print(df["Weight"].isna().sum())       # Count of NULL weights
print(df["SellEndDate"].isna().sum())  # Count of NULL dates

# Stage the data in a temp table to avoid mutating the source table
cursor.execute("CREATE TABLE #ProductWeights (Name NVARCHAR(100), Weight DECIMAL(8, 2) NULL)")

# Convert NaN back to None so NULL values round-trip correctly
for _, row in df.iterrows():
    weight = None if pd.isna(row["Weight"]) else float(row["Weight"])
    cursor.execute(
        "INSERT INTO #ProductWeights (Name, Weight) VALUES (%(name)s, %(weight)s)",
        {"name": row["Name"], "weight": weight}
    )

Warning

Vergelijk het niet met == np.nan of == pd.NaT. Deze vergelijkingen retourneren altijd False. Gebruik pd.isna() of pd.notna() in plaats daarvan.

Afhandeling van null-waarden in Polars

Polars gebruikt een eigen null-waarde (niet NaN), die rechtstreeks overeenkomt met Python None:

import polars as pl

cursor.execute("SELECT Name, Weight, Color FROM Production.Product")
table = cursor.arrow()
df = pl.from_arrow(table)

# Filter rows with non-null values
has_weight = df.filter(pl.col("Weight").is_not_null())

# Replace null with a default
df = df.with_columns(pl.col("Color").fill_null("No color"))