Templates › Data explorer

Data explorer for Snowflake tables (Streamlit template)

Browse the tables in a Snowflake schema, profile columns, filter rows, group and chart, and download what you find. A read-only Streamlit template.

General purposeStreamlitRuns in Snowflake153 lines of Python
Live demo: the real app, running in your browser on generated sample data

Click Run to start the app here.

The first start downloads Python for the browser (about 30 MB) and takes 10–30 seconds.

What it answers

Not every question needs a dashboard. This template lets people browse the tables in one schema, see a profile of each column (type, empty values, distinct values, minimum and maximum), filter rows, group and chart, and download the result.

It is for teams who want to give colleagues a safe look at a schema without handing out SQL access.

What's in it

  • Table picker for a schema (read-only, row limit)
  • Column profile (type, empty, distinct, min/max, example)
  • Filter by any column; CSV download
  • Group by a column and chart counts, sums or averages

The data it needs

Schema

Not bound to fixed columns — set DATABASE and SCHEMA in the DATA section and DEMO = False.

Using it on your data

It isn't tied to fixed columns: set the database and schema at the top. It only reads, and it limits the number of rows, so a careless filter doesn't scan a billion-row table.

In StreamGen you don't edit any of this by hand: the agent looks at your tables, matches columns by name and type (including the names above), shows you the mapping, and checks the app on your live data before you deploy it.

Three ways to use it

Try it in StreamGen

Two hours on sample data in a ready-made Snowflake sandbox. No sign-up, nothing to install.

Start the 2-hour try

Install in your Snowflake

StreamGen is a Snowflake Native App: it runs inside your account, and your data stays there.

Open the Marketplace listing

Copy the code

It's a plain Streamlit app. Paste it into Streamlit in Snowflake, set DEMO = False and point the query at your table.

Show the code

The code

All of it, as it runs in the demo above. The data section at the top is the only part that changes for your tables.

Show all 153 lines
"""Data explorer — browse the tables in a schema: profile columns, filter,
group and chart, and download what you find."""

import numpy as np
import pandas as pd
import plotly.express as px
import streamlit as st

st.set_page_config(page_title="Data explorer", layout="wide")

# ── DATA ──────────────────────────────────────────────────────────────────────
# DEMO = True explores generated sample tables. Set DEMO = False to explore
# the tables in DATABASE.SCHEMA (read-only; at most ROW_LIMIT rows per table).
DEMO = True
DATABASE = "{{DATABASE}}"
SCHEMA = "{{SCHEMA}}"
TABLES_SQL = "SHOW TABLES IN SCHEMA {{DATABASE}}.{{SCHEMA}}"
ROW_LIMIT = 50_000
# ──────────────────────────────────────────────────────────────────────────────


def demo_tables() -> dict:
    rng = np.random.default_rng(1)
    n = 2000
    customers = pd.DataFrame({
        "CUSTOMER_ID": np.arange(1, 301),
        "SEGMENT": rng.choice(["Enterprise", "Mid-market", "SMB"], 300, p=[0.15, 0.35, 0.5]),
        "COUNTRY": rng.choice(["DE", "US", "UK", "FR", "NL"], 300),
        "SIGNUP_DATE": pd.Timestamp.today().normalize() - pd.to_timedelta(rng.integers(0, 1500, 300), unit="D"),
    })
    orders = pd.DataFrame({
        "ORDER_ID": np.arange(1, n + 1),
        "CUSTOMER_ID": rng.integers(1, 301, n),
        "ORDER_DATE": pd.Timestamp.today().normalize() - pd.to_timedelta(rng.integers(0, 365, n), unit="D"),
        "STATUS": rng.choice(["shipped", "open", "returned"], n, p=[0.8, 0.15, 0.05]),
        "AMOUNT": rng.gamma(2, 180, n).round(2),
    })
    return {"CUSTOMERS": customers, "ORDERS": orders}


@st.cache_data(ttl=600, show_spinner=False)
def list_tables() -> list:
    if DEMO:
        return sorted(demo_tables())
    from snowflake.snowpark.context import get_active_session
    rows = get_active_session().sql(TABLES_SQL).collect()
    return sorted(r["name"] for r in rows)


@st.cache_data(ttl=600, show_spinner=False)
def load_table(name: str) -> pd.DataFrame:
    if DEMO:
        return demo_tables()[name]
    from snowflake.snowpark.context import get_active_session
    # name comes from SHOW TABLES; the list form quotes each part safely
    return get_active_session().table([DATABASE, SCHEMA, name]).limit(ROW_LIMIT).to_pandas()


def profile(df: pd.DataFrame) -> pd.DataFrame:
    rows = []
    for c in df.columns:
        s = df[c]
        numeric = pd.api.types.is_numeric_dtype(s)
        rows.append({
            "COLUMN": c, "TYPE": str(s.dtype), "EMPTY": int(s.isna().sum()), "DISTINCT": int(s.nunique()),
            "MIN": s.min() if numeric or pd.api.types.is_datetime64_any_dtype(s) else None,
            "MAX": s.max() if numeric or pd.api.types.is_datetime64_any_dtype(s) else None,
            "EXAMPLE": str(s.dropna().iloc[0])[:60] if s.notna().any() else "",
        })
    out = pd.DataFrame(rows)
    for c in ("MIN", "MAX"):
        out[c] = out[c].astype(str).replace({"None": "", "NaT": "", "nan": ""})
    return out


st.title("Data explorer")
st.caption("Demo tables — set DEMO = False in the DATA section to explore your schema." if DEMO else f"{DATABASE}.{SCHEMA}")

try:
    tables = list_tables()
except Exception as e:
    st.error(f"Could not list tables: {e}")
    st.stop()
if not tables:
    st.info("No tables in this schema.")
    st.stop()

with st.sidebar:
    table = st.selectbox("Table", tables)

try:
    df = load_table(table)
except Exception as e:
    st.error(f"Could not read {table}: {e}")
    st.stop()
for c in df.columns:  # dates often arrive as strings
    if df[c].dtype == object and ("DATE" in c.upper() or c.upper().endswith("_AT")):
        df[c] = pd.to_datetime(df[c], errors="coerce")

k = st.columns(3)
k[0].metric("Rows loaded", f"{len(df):,}", "limit reached" if len(df) >= ROW_LIMIT else None, delta_color="off")
k[1].metric("Columns", f"{df.shape[1]}")
k[2].metric("Empty cells", f"{int(df.isna().sum().sum()):,}")

tab_data, tab_profile, tab_chart = st.tabs(["Rows", "Columns", "Group & chart"])

with tab_data:
    filtered = df
    col = st.selectbox("Filter column", ["(none)"] + list(df.columns))
    if col != "(none)":
        s = df[col]
        if pd.api.types.is_numeric_dtype(s) and s.notna().any():
            lo, hi = float(s.min()), float(s.max())
            rng_sel = st.slider("Range", lo, hi, (lo, hi)) if lo < hi else (lo, hi)
            filtered = df[s.between(*rng_sel)]
        else:
            values = sorted(s.dropna().astype(str).unique())[:500]
            picked = st.multiselect("Values", values)
            if picked:
                filtered = df[s.astype(str).isin(picked)]
    st.caption(f"{len(filtered):,} rows")
    st.dataframe(filtered.head(2000).reset_index(drop=True), width="stretch")
    st.download_button("Download CSV", filtered.to_csv(index=False), f"{table.lower()}.csv", "text/csv")

with tab_profile:
    st.dataframe(profile(df), width="stretch")

with tab_chart:
    dims = [c for c in df.columns if not pd.api.types.is_numeric_dtype(df[c]) or df[c].nunique() <= 30]
    measures = [c for c in df.columns if pd.api.types.is_numeric_dtype(df[c])]
    if not dims:
        st.info("No column to group by.")
    else:
        c1, c2, c3 = st.columns(3)
        dim = c1.selectbox("Group by", dims)
        how = c2.selectbox("Measure", ["Row count"] + [f"Sum of {m}" for m in measures] + [f"Average of {m}" for m in measures])
        top = c3.slider("Show top", 5, 50, 15)
        key = df[dim].dt.to_period("M").dt.to_timestamp() if pd.api.types.is_datetime64_any_dtype(df[dim]) else df[dim].astype(str)
        if how == "Row count":
            g = df.groupby(key).size().rename("VALUE")
        else:
            agg, m = how.split(" of ", 1)
            g = df.groupby(key)[m].agg("sum" if agg == "Sum" else "mean").rename("VALUE")
        g = g.reset_index().rename(columns={g.index.name or dim: "GROUP"})
        g.columns = ["GROUP", "VALUE"]
        if pd.api.types.is_datetime64_any_dtype(df[dim]):
            fig = px.line(g.sort_values("GROUP"), x="GROUP", y="VALUE", markers=True, labels={"GROUP": dim, "VALUE": how})
        else:
            g = g.sort_values("VALUE", ascending=False).head(top)
            fig = px.bar(g, x="GROUP", y="VALUE", labels={"GROUP": dim, "VALUE": how})
        fig.update_layout(margin=dict(t=30, b=10))
        st.plotly_chart(fig, width="stretch")

Questions

Can people run their own SQL?

Not in the template, on purpose. It only reads tables in the schema you choose, within the row limit.

Which tables do people see?

Only those their Snowflake role can read, so the same rules apply as in a worksheet.

Can I use the code without StreamGen?

Yes. It is a plain Streamlit app. In Snowsight, create a Streamlit app, paste the code, add plotly to its packages, set DEMO = False and point the query at your table. StreamGen does that mapping, the checks and the deploy for you, and keeps the app working afterwards.

Does my data leave Snowflake?

No. In Snowflake the app runs inside your account and queries your tables there. The live demo on this page runs in your browser on generated sample data; nothing is sent anywhere.

Warehouse or container runtime?

Both work. The template only needs pandas, numpy and plotly, which both Streamlit in Snowflake runtimes provide.

Related templates

All templates · Guides

Build it on your own Snowflake data

In StreamGen you pick this template, the agent matches it to your tables, checks it, and deploys it to Snowflake with roles, approvals and an audit trail. Then ask for changes in plain words.

No sign-up for the 2-hour try. The Native App is free to install, with a free 7-day trial key.