Query a warehouse

Runs in your browserBrowser compatible

Answer business questions in SQL: totals, month-over-month growth and top products with window functions, then chart and export. Swap in your own warehouse.

Run it

What you get: revenue by region

regionorderscustomerstotal
East933431,614.93
North713224,486.76
West432514,083.23
South332313,200.27

Output of the revenue-by-region query on the sample sales.csv (240 orders).

The notebook

A read-only preview. Nothing here runs.

  1. # Query a warehouse Answer business questions in SQL and keep the results as DataFrames you can chart and export. This notebook loads `sales.csv` (240 orders across 2025) into a SQLite database, so it runs here with no signup and nothing to connect. The queries are ordinary SQL: the same patterns work on Postgres, Snowflake, BigQuery and Redshift once you point `conn` at one (the last section shows how, and which functions to change). You will: look at the schema, aggregate, compute month-over-month growth with a CTE and a window function, find the top product per region, pass a parameter safely, then chart and export the result.

  2. import sqlite3
    
    import pandas as pd
    
    conn = sqlite3.connect(":memory:")  # swap for your warehouse connection (see the last section)
    sales = pd.read_csv("sales.csv")
    sales.to_sql("sales", conn, index=False)
    
    
    def q(sql, params=()):
        """Run SQL and return the result as a DataFrame."""
        return pd.read_sql(sql, conn, params=params)
    
    
    print(f"Loaded {len(sales):,} orders into a table called sales.")
    q("SELECT * FROM sales LIMIT 5")
  3. ## Know the table first Before writing a query, check the column names and types. In a real warehouse this is `DESCRIBE` or `information_schema.columns`; SQLite spells it `PRAGMA table_info`.

  4. q("PRAGMA table_info(sales)")[["name", "type"]]
  5. ## Aggregate: which region earns the most? `GROUP BY` collapses rows into one per region. `COUNT(DISTINCT ...)` counts customers once however many orders they placed.

  6. by_region = q("""
        SELECT region,
               COUNT(*)                    AS orders,
               COUNT(DISTINCT customer_id) AS customers,
               ROUND(SUM(amount), 2)       AS total
        FROM sales
        GROUP BY region
        ORDER BY total DESC
    """)
    by_region
  7. ## CTE and window function: month-over-month growth A CTE (`WITH ... AS`) names an intermediate result so the final query stays readable. `LAG(total)` looks at the previous row in month order, which is how you compare each month with the one before without a self-join.

  8. monthly = q("""
        WITH monthly AS (
            SELECT substr(order_date, 1, 7) AS month,
                   SUM(amount)              AS total
            FROM sales
            GROUP BY month
        )
        SELECT month,
               ROUND(total, 2) AS total,
               ROUND(100.0 * (total - LAG(total) OVER (ORDER BY month))
                     / LAG(total) OVER (ORDER BY month), 1) AS growth_pct
        FROM monthly
        ORDER BY month
    """)
    monthly
  9. The first month has no previous month, so `growth_pct` is `NULL` (shown as `NaN`). That is correct, not a bug: handle it explicitly rather than filling it with 0.

  10. ## Top product per region `ROW_NUMBER() OVER (PARTITION BY region ORDER BY ...)` ranks products inside each region. Filtering on that rank in an outer query keeps only the winner, which is the standard "top N per group" pattern.

  11. q("""
        SELECT region, product, total
        FROM (
            SELECT region,
                   product,
                   ROUND(SUM(amount), 2) AS total,
                   ROW_NUMBER() OVER (PARTITION BY region ORDER BY SUM(amount) DESC) AS rnk
            FROM sales
            GROUP BY region, product
        )
        WHERE rnk = 1
        ORDER BY total DESC
    """)
  12. ## Pass values as parameters Never build SQL by pasting a value into the string: it breaks on quotes and is how SQL injection happens. Put a placeholder in the query and pass the value separately. SQLite uses `?`; other drivers use `%s` or `:name`.

  13. region = "East"
    
    q("""
        SELECT customer_id,
               COUNT(*)              AS orders,
               ROUND(SUM(amount), 2) AS total
        FROM sales
        WHERE region = ?
        GROUP BY customer_id
        ORDER BY total DESC
        LIMIT 5
    """, (region,))
  14. ## Chart the answer Do the heavy lifting in SQL (one row per month and region), then reshape the small result in pandas for plotting.

  15. import matplotlib.pyplot as plt
    
    by_month_region = q("""
        SELECT substr(order_date, 1, 7) AS month, region, SUM(amount) AS total
        FROM sales
        GROUP BY month, region
    """)
    pivot = by_month_region.pivot(index="month", columns="region", values="total")
    
    ax = pivot.plot(figsize=(9, 4), marker="o", title="Monthly revenue by region")
    ax.set_ylabel("Revenue")
    plt.tight_layout()
    plt.show()
    
    best = pivot.sum().idxmax()
    print(f"{best} leads with {pivot[best].sum():,.2f} across {len(pivot)} months.")
  16. ## Export the result A query result is a DataFrame, so it saves like any other. The file lands in the project's files; the link downloads it to your computer.

  17. from base64 import b64encode
    
    from IPython.display import HTML
    
    monthly.to_csv("monthly_revenue.csv", index=False)
    print("Saved monthly_revenue.csv to the project files.")
    
    data = monthly.to_csv(index=False).encode()
    HTML(f'<a download="monthly_revenue.csv" href="data:text/csv;base64,{b64encode(data).decode()}">Download monthly_revenue.csv</a>')
  18. ## Point it at your own warehouse The browser kernel cannot reach the network or hold secrets, so to query a real database sign up (top right) to carry this notebook into a project on real compute, then: 1. Add your connection string as a project secret named `WAREHOUSE_URL`. Keep it out of the notebook. 2. Install the driver in a cell and connect through SQLAlchemy: ~~~python %pip install sqlalchemy psycopg2-binary # Snowflake: snowflake-sqlalchemy, BigQuery: sqlalchemy-bigquery import os from sqlalchemy import create_engine, text conn = create_engine(os.environ["WAREHOUSE_URL"]) # e.g. postgresql://user:pass@host:5432/dbname def q(sql, params=None): return pd.read_sql(text(sql), conn, params=params) ~~~ 3. Delete the `sales.to_sql(...)` line (your table already exists), change `?` placeholders to `:name` (for example `WHERE region = :region` with `{"region": region}`), and re-run. Date and string functions are where dialects differ. `substr(order_date, 1, 7)` becomes `date_trunc('month', order_date)` on Postgres, Snowflake and Redshift, or `FORMAT_DATE('%Y-%m', order_date)` on BigQuery. Window functions, CTEs and `GROUP BY` work unchanged. ## Your turn 1. Which month had the biggest drop, and which region caused it? Group the monthly query by region as well. 2. Show the top 3 products per region instead of 1 (change the `WHERE rnk` filter). 3. Add a running total with `SUM(total) OVER (ORDER BY month)`.

Runtime requirements

Python
Python 3.12 (in-browser) or the Python data science environment
Packages
pandas, matplotlib
Sample data
sales.csv
Environment
Python data science · CPU

Browser or real compute

In your browser this notebook runs on a small Python with limited memory and no installs. A ByteRun project runs the same notebook on a full machine with your files saved, any package, and more memory when you need it.

Start the 60-day free trial with this template