SQL and Python: Analyze a Database and Create a PDF Report
SQL and Python on one job: build a SQLite sales database, query it from Python into pandas, chart each result with Plotly, and place the charts in a PDF report with fpdf2. SQL does the joins and aggregation, Python handles the plotting and the layout.
Table of contents
The database
The example is an online store with three tables: sales, products and customers. I use SQLite, which stores the whole database in a single file and ships with Python, so there is nothing extra to install for the database part.
- sales: one row per sale with the date, customer, product, quantity, unit price and total price. Its
customer_idandproduct_idcolumns are foreign keys that point to the other two tables. - products: product ID (the primary key), product name and unit cost.
- customers: customer ID (the primary key), first name, last name, email and phone number.
Create the database
One Python script creates the three tables and fills them with sample data: five products, ten customers and 1,000 random sales across 2022. Connecting to sales.db creates the file if it does not exist yet.
Each CREATE TABLE statement lists the columns and their data types. The INSERT statements use ? placeholders, and the loop at the end generates the random sales before the script commits.
import sqlite3
import random
import datetime
# Define SQL commands for creating the tables
create_sales_table = '''CREATE TABLE sales (
sale_id INTEGER PRIMARY KEY,
sale_date DATE,
customer_id INTEGER,
product_id INTEGER,
quantity INTEGER,
unit_price DECIMAL(10, 2),
total_price DECIMAL(10, 2),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
FOREIGN KEY (product_id) REFERENCES products(product_id)
)'''
create_products_table = '''CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
product_name TEXT,
unit_cost DECIMAL(10, 2)
)'''
create_customers_table = '''CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
first_name TEXT,
last_name TEXT,
email TEXT,
phone TEXT
)'''
# Define SQL commands for inserting sample data into the tables
insert_products_data = '''INSERT INTO products (product_name, unit_cost) VALUES (?, ?)'''
insert_sales_data = '''INSERT INTO sales (sale_date, customer_id, product_id, quantity, unit_price, total_price) VALUES (?, ?, ?, ?, ?, ?)'''
insert_customers_data = '''INSERT INTO customers (first_name, last_name, email, phone) VALUES (?, ?, ?, ?)'''
# Define sample data for the products and customers tables
products = [('Product A', 50.00), ('Product B', 25.00), ('Product C', 75.00), ('Product D', 40.00), ('Product E', 60.00)]
customers = [
('John', 'Doe', 'johndoe@example.com', '555-1234'),
('Jane', 'Doe', 'janedoe@example.com', '555-5678'),
('Bob', 'Smith', 'bobsmith@example.com', '555-9012'),
('Alice', 'Jones', 'alicejones@example.com', '555-3456'),
('David', 'Brown', 'davidbrown@example.com', '555-7890'),
('Emily', 'Davis', 'emilydavis@example.com', '555-2345'),
('Frank', 'Wilson', 'frankwilson@example.com', '555-6789'),
('Grace', 'Lee', 'gracelee@example.com', '555-1234'),
('Henry', 'Chen', 'henrychen@example.com', '555-5678'),
('Isabel', 'Garcia', 'isabelgarcia@example.com', '555-9012')
]
# Define the start and end dates for generating sales data
start_date = datetime.date(2022, 1, 1)
end_date = datetime.date(2022, 12, 31)
# Connect to the database and create the tables
with sqlite3.connect('sales.db') as conn:
# Create the sales table
conn.execute(create_sales_table)
# Create the products table
conn.execute(create_products_table)
# Create the customers table
conn.execute(create_customers_table)
# Insert sample data into the products table
for product in products:
conn.execute(insert_products_data, product)
# Insert sample data into the customers table
for customer in customers:
conn.execute(insert_customers_data, customer)
# Insert sample data into the sales table
for i in range(1000):
sale_date = start_date + datetime.timedelta(days=random.randint(0, 364))
customer_id = random.randint(1, len(customers))
product_id = random.randint(1, len(products))
quantity = random.randint(1, 10)
unit_price = products[product_id-1][1]
total_price = quantity * unit_price
conn.execute(insert_sales_data, (sale_date, customer_id, product_id, quantity, unit_price, total_price))
# Commit the changes
conn.commit()
print("Database successfully created!")
Database successfully created!
To check the result, open sales.db in an SQLite viewer such as the free SQLite Viewer web app. The sales table holds the 1,000 records, and the products and customers tables hold the sample data.

Set up the notebook
The analysis runs in a Jupyter notebook with four packages: pandas for the data, Plotly Express for the charts, Kaleido to save the charts as images, and fpdf for the PDF. Install them with pip install pandas plotly kaleido fpdf2.
The video installs the original fpdf package, whose last release is from 2015. Its maintained successor fpdf2 uses the same from fpdf import FPDF import, so the code below runs with either. The cell also picks Plotly’s “presentation” template for clean charts and creates an output folder next to the notebook for the images and the PDF.
from datetime import date
from pathlib import Path
import sqlite3
import pandas as pd # pip install pandas
import plotly.express as px # pip install plotly-express kaleido
from fpdf import FPDF # pip install fpdf
# Define the plotly template. Some other examples:
# "plotly", "ggplot2", "seaborn", "simple_white", "plotly_dark", "plotly_white", ..
plotly_template = "presentation"
# Define the paths
current_dir = Path(__file__).parent if "__file__" in locals() else Path.cwd()
database_path = current_dir / "sales.db"
output_dir = current_dir / "output"
# Create the output directory and its parent directory if they do not exist
output_dir.mkdir(parents=True, exist_ok=True)
Monthly sales
Connect with sqlite3.connect, write the query as a string, and pass both to pd.read_sql_query. The result is a pandas DataFrame. This first query sums the sales per day.
# Create a connection to the database
conn = sqlite3.connect(database_path)
# Execute the query and load results into a Pandas DataFrame
query = '''
SELECT sale_date, SUM(total_price) as total_sales
FROM sales
GROUP BY sale_date
ORDER BY sale_date ASC
'''
df = pd.read_sql_query(query, conn)
# Print the DataFrame
print(df)
sale_date total_sales
0 2022-01-01 1095
1 2022-01-02 555
2 2022-01-03 150
3 2022-01-04 975
4 2022-01-06 395
.. ... ...
335 2022-12-26 1315
336 2022-12-27 685
337 2022-12-28 1545
338 2022-12-29 740
339 2022-12-31 850
[340 rows x 2 columns]
To get monthly totals, convert sale_date to a datetime, make it the index, and resample to month ends. Recent pandas versions need the alias 'ME' for month end; the plain 'M' from the video is deprecated in pandas 2.2 and rejected in pandas 3.
# Convert sale_date to datetime
df['sale_date'] = pd.to_datetime(df['sale_date'])
df.info()
# Set the sale_date column as the index
df = df.set_index('sale_date')
df.head(3)
# Resample the data to a monthly frequency and compute the sum
df_monthly = df.resample('ME').sum()
df_monthly
total_sales
sale_date
2022-01-31 23600
2022-02-28 22400
2022-03-31 29660
2022-04-30 19225
2022-05-31 30015
2022-06-30 24395
2022-07-31 27525
2022-08-31 20835
2022-09-30 19285
2022-10-31 14945
2022-11-30 23855
2022-12-31 24140
Add a short month name for the x axis, draw a bar chart, and save it as a PNG in the output folder. The PDF step later picks up every PNG in that folder.
# Map the month number to short month name
df_monthly['month_name'] = df_monthly.index.strftime('%b')
df_monthly
# Create the Plotly figure with text parameter
fig = px.bar(df_monthly,
x='month_name',
y='total_sales',
template=plotly_template,
text='total_sales')
# Set the layout
fig.update_layout(
title='Total Sales by Month',
xaxis_title='Month',
yaxis_title='Total Sales ($)',
yaxis_tickprefix='$',
)
# Show the plot
fig.show()
# Save the chart as a PNG image
fig.write_image(output_dir / 'monthly_sales.png',
width=1200,
height=400,
scale=4)
Sales by product
This query joins the products table onto the sales table and sums the sales per product name. The aggregation happens in SQL, so pandas only receives five rows.
# Execute the query and load results into a Pandas DataFrame
query = '''
SELECT p.product_name, SUM(s.total_price) as total_sales
FROM sales s
JOIN products p ON s.product_id = p.product_id
GROUP BY p.product_name
'''
df = pd.read_sql_query(query, conn)
df
product_name total_sales
0 Product A 58850
1 Product B 25350
2 Product C 84600
3 Product D 42320
4 Product E 68760
The chart code is the same as before with a different x column, title and file name.
# Create the Plotly figure with text parameter
fig = px.bar(df,
x='product_name',
y='total_sales',
template=plotly_template,
text='total_sales')
# Set the layout
fig.update_layout(
title='Total Sales by Product',
xaxis_title='Product',
yaxis_title='Total Sales ($)',
yaxis_tickprefix='$',
)
# Show the plot
fig.show()
# Save the chart as a PNG image
fig.write_image(output_dir / 'product_sales.png',
width=1200,
height=400,
scale=4)
Top customers
The last query joins the customers table, combines first and last name with SQLite’s || operator, orders the customers by sales and keeps the top 10 with LIMIT.
# Execute the query and load results into a Pandas DataFrame
query = '''
SELECT c.first_name || ' ' || c.last_name as customer_name, SUM(s.total_price) as total_sales
FROM sales s
JOIN customers c ON s.customer_id = c.customer_id
GROUP BY customer_name
ORDER BY total_sales DESC
LIMIT 10
'''
df = pd.read_sql_query(query, conn)
# Create the Plotly figure
fig = px.bar(df,
x='customer_name',
y='total_sales',
template=plotly_template,
text='total_sales')
# Set the layout
fig.update_layout(
title='Top Customers by Sales',
xaxis_title='Customer',
yaxis_title='Total Sales ($)',
yaxis_tickprefix='$',
)
# Show the plot
fig.show()
# Save the chart as a PNG image
fig.write_image(output_dir / 'customer_sales.png',
width=1200,
height=400,
scale=4)

Build the PDF report
The report collects every PNG in the output folder and places the charts one below the other on an A4 page, under a title with today’s date. pdf.w - 20 makes each image as wide as the page minus a 10 mm margin on each side.
# Define the font color as RGB values (dark gray)
font_color = (64, 64, 64)
# Find all PNG files in the output folder
chart_filenames = [str(chart_path) for chart_path in output_dir.glob("*.png")]
# Create a PDF document and set the page size
pdf = FPDF()
pdf.add_page()
pdf.set_font('Arial', 'B', 24)
# Add the overall page title
title = f"Sales Report as of {date.today().strftime('%m/%d/%Y')}"
pdf.set_text_color(*font_color)
pdf.cell(0, 20, title, align='C', ln=1)
# Add each chart to the PDF document
for chart_filename in chart_filenames:
pdf.ln(10) # Add padding at the top of the next chart
pdf.image(chart_filename, x=None, y=None, w=pdf.w - 20, h=0)
# Save the PDF document to a file on disk
pdf.output(output_dir / "sales_report.pdf", "F")
The result is output/sales_report.pdf with the three charts. The charts appear in the order glob returns the files, so prefix the file names with numbers if the order matters.
SQL or pandas
Both work, and the choice is mostly about where the data lives. Aggregating in SQL sends less data to Python, which matters on large tables; pandas is easier to explore step by step. Segmenting customers by sales shows the two side by side.
In SQL, a CASE statement assigns the segment while grouping:
# Execute the query and load results into a Pandas DataFrame
query = '''
SELECT
customers.customer_id,
customers.first_name || ' ' || customers.last_name as customer_name,
SUM(sales.total_price) as total_sales,
CASE
WHEN SUM(sales.total_price) > 30000 THEN 'High Value'
WHEN SUM(sales.total_price) > 26000 THEN 'Medium Value'
ELSE 'Low Value'
END as customer_segment
FROM sales
INNER JOIN customers ON sales.customer_id = customers.customer_id
GROUP BY customers.customer_id
ORDER BY total_sales DESC
'''
df = pd.read_sql_query(query, conn)
df
In pandas, the query only sums the sales, and pd.cut assigns the segments afterwards:
# Execute the query and load results into a Pandas DataFrame
query = '''
SELECT
customers.customer_id,
customers.first_name || ' ' || customers.last_name as customer_name,
SUM(sales.total_price) as total_sales
FROM sales
INNER JOIN customers ON sales.customer_id = customers.customer_id
GROUP BY customers.customer_id
'''
df = pd.read_sql_query(query, conn)
df
# Group the data by customer segment
bins = [0, 26000, 30000, float('inf')]
labels = ['Low Value', 'Medium Value', 'High Value']
df['customer_segment'] = pd.cut(df['total_sales'], bins=bins, labels=labels)
# Order the data by total sales
df = df.sort_values(by='total_sales', ascending=False)
df
The pandas side of these aggregations maps closely to Excel, as I show in SUMIFS and AVERAGEIFS in pandas. If you want SQL inside a spreadsheet instead, see how to run SQL queries in Excel like a formula.
Close the connection
Close the connection when you are done to free the database file. The sqlite3 connection works as a context manager, but that only commits or rolls back the transaction and leaves the connection open.
# Close the connection
conn.close()
In a script, contextlib.closing() closes the connection for you when the block ends:
import sqlite3
from contextlib import closing
import pandas as pd
# Define the query to be executed
query = '''
SELECT p.product_name, SUM(s.total_price) as total_sales
FROM sales s
JOIN products p ON s.product_id = p.product_id
GROUP BY p.product_name
'''
# closing() makes sure the connection is closed when the block ends
with closing(sqlite3.connect('sales.db')) as conn:
df = pd.read_sql_query(query, conn)
# Print the DataFrame with the results
print(df)
Troubleshooting
- Invalid frequency: M. pandas 3 removed the
'M'alias. Use'ME'as shown above. - DeprecationWarning about fonts, ln or dest with fpdf2. fpdf2 substitutes Helvetica for Arial and warns about
ln=1and the"F"argument. The PDF is still written; the warnings only announce future removals. - The default date adapter is deprecated. Python 3.12 warns when sqlite3 stores
datetime.datevalues directly. The database is still created correctly. - table sales already exists. The create script runs once. Delete
sales.dbbefore running it again.
Resources
- Source code on GitHub (database script, notebook and sample output)
