Export SQLite Query Results to CSV in Python

Connects to a SQLite database, runs a query, and writes the result rows and column headers to a CSV file using the standard library.

Easy Python 3.9+ Aug 9, 2026 Files & data 17 views 0 copies

Python code

35 lines
Python 3.9+
import sqlite3
import csv

def export_query_to_csv(db_path, query, csv_path):
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    cursor.execute(query)

    rows = cursor.fetchall()
    column_names = [description[0] for description in cursor.description]

    with open(csv_path, 'w', newline='', encoding='utf-8') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(column_names)
        writer.writerows(rows)

    conn.close()
    print(f"Exported {len(rows)} rows to {csv_path}")

if __name__ == "__main__":
    # Create a sample in-memory database and export
    conn = sqlite3.connect(':memory:')
    conn.execute("CREATE TABLE employees (id INTEGER, name TEXT, department TEXT)")
    conn.executemany(
        "INSERT INTO employees VALUES (?, ?, ?)",
        [(1, 'Alice', 'Engineering'), (2, 'Bob', 'Marketing'), (3, 'Carol', 'Sales')]
    )
    conn.commit()
    conn.close()

    export_query_to_csv(
        ':memory:',
        "SELECT * FROM employees WHERE department != 'Sales'",
        'employees_export.csv'
    )

Output

stdout
Exported 2 rows to employees_export.csv

How it works

The sqlite3 module handles the database connection and query execution. cursor.description provides column names from the result metadata. Using csv.writer with newline='' prevents extra blank lines in the CSV file. Encoding is set to UTF-8 for widespread compatibility. The function is reusable for any database path and query.

Common mistakes

  • Forgetting `newline=''` in `open()`, which adds blank lines between rows.
  • Not closing the connection if an exception occurs—use a context manager.
  • Assuming query results always have headers; use `cursor.description` safely.

Variations

  1. Use `conn.cursor().execute(query)` and `fetchmany(size)` for large datasets to avoid loading all rows into memory.
  2. Wrap `export_query_to_csv` with a `try/finally` or context manager to guarantee connection closure.

Real-world use cases

  • Generating weekly sales reports from a production database to share with stakeholders.
  • Backing up a subset of data from a database into a CSV for archival or migration.
  • Exporting user lists or audit logs for compliance or offline analysis.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.