AI Hints
Home›PostgreSQL Tutorial›COPY, Pools and a Python Report
PostgreSQL · Lesson 87 of 120

Practice: A Python Report

Query, then format.

⏱ 2 min read▶ Video at 1:18:25🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

The owner wants a small weekly text report, top genres by revenue, with a little bar chart made of characters. Let's write it in Python.

  • Top genres
  • Revenue
  • Text bars

The genre report

Row factory dict row gives each row as a dictionary. We query revenue per genre, then print each with a bar scaled to the biggest. Run it. A neat report, ready to email.

report.pypython
import psycopg
from psycopg.rows import dict_row

URL = "postgresql://postgres:postgres@localhost:5432/riverside"
with psycopg.connect(URL, row_factory=dict_row) as conn:
    rows = conn.execute("""
        SELECT b.genre, sum(i.quantity * b.price) AS revenue
        FROM order_items i JOIN books b USING (book_id)
        GROUP BY b.genre ORDER BY revenue DESC LIMIT 5""").fetchall()

top = rows[0]["revenue"]
for r in rows:
    bar = "#" * int(30 * r["revenue"] / top)
    print(f'{r["genre"]:<11} {r["revenue"]:>9,.2f}  {bar}')
Output
Technology   9,576.04  ##############################
Fantasy      7,927.05  ########################
Mystery      7,440.86  #######################
Thriller     6,443.11  ####################
Business     5,149.63  ################

What we used

Parameters keep it safe. Dict rows make code readable. The SQL does the heavy lifting, and Python just formats. Schedule it with cron, and email it every Monday.

keyvalue
dict_rowreadable rows
SQLdoes the maths
Pythonformats
cronevery Monday

Summary

Let SQL do the work, and Python format the result. Next, partitioning big tables.

Key takeaways
  • dict_row
  • SQL first
  • Format in Python
Next up: Partitioning — split big tables