Skip to main content

How to Set Up a Daily PostHog to Snowflake Data Pull

PostHog can already push its own product events out to a data warehouse. This article covers the opposite direction: a scheduled Snowflake job that reaches into PostHog, runs a query, and lands the results in Snowflake tables. We walk through it end to end using Google Search Console data synced into PostHog’s Data Warehouse, and the same pattern works for any other source PostHog has connected.

The pattern: network rule → secret → external access integration → Python stored procedure → scheduled Task.

When to use this

PostHog’s built-in batch export only knows about PostHog’s own events. It doesn’t export the other sources PostHog has synced into its Data Warehouse, such as Google Ads, Meta Ads, TikTok Ads, or Google Search Console. A pull-based job that runs on the Snowflake side can query any of those sources the same way, on your own schedule, into your own tables.

About PostHog’s Data Warehouse and HogQL

PostHog’s Data Warehouse connects to external sources, syncs their data, and makes it queryable alongside your product events through HogQL, PostHog’s SQL dialect. HogQL is a safety-checked layer over ClickHouse SQL, so once a source is connected, a query like SELECT * FROM googlesearchconsole.search_analytics_by_date works through PostHog’s query API. You don’t need a separate warehouse connection or separate credentials.

Check the real table names first. You can’t reliably guess table names from a source’s product name. For example, you might expect Google Search Console tables called sites or sitemaps, but what actually syncs is a set of seven search_analytics_by_… tables. Look up the exact names in PostHog’s Data Warehouse sidebar before you write the pull query.

How it works

A Snowflake Task runs daily and calls a Python stored procedure. The procedure reads the PostHog API key from a Snowflake secret, makes outbound calls through an external access integration, and sends one HogQL query per table to PostHog’s query API. It then replaces each table’s data in Snowflake with the parsed columns from the response.

Terminology note: this is not Snowpipe. Snowpipe loads files automatically as they land in cloud storage. It can’t call an external API on a timer. This setup uses a Task (a cron schedule) that calls a stored procedure, which gives you the same daily refresh.

Prerequisites

  • A PostHog project with at least one Data Warehouse source connected (this article uses Google Search Console), and that project’s ID.
  • A PostHog personal API key with the Query: Read scope.
  • A Snowflake role that can create network rules, secrets, and external access integrations, such as ACCOUNTADMIN or a role granted CREATE INTEGRATION.
  • A Snowflake database for the landed data and a warehouse for the scheduled task. The examples use POSTHOG and POSTHOG_WH.

Steps

The examples below use PostHog US Cloud (us.posthog.com) and a database named POSTHOG. Adjust the names to fit your environment.

Step 0: Create a PostHog API key with query access

In PostHog, go to Settings → Personal API Keys. You can reuse an existing key, but check its scopes: the default scopes do not include query access. Add Query: Read explicitly. Without it, every call fails with a permissions error that doesn’t tell you much.

Step 1: Allow Snowflake to call PostHog

-- Allow outbound HTTPS to PostHog's US Cloud API
CREATE OR REPLACE NETWORK RULE POSTHOG.PUBLIC.POSTHOG_NETWORK_RULE
  MODE = EGRESS
  TYPE = HOST_PORT
  VALUE_LIST = ('us.posthog.com');

If your project is on PostHog EU Cloud, use eu.posthog.com here and in the procedure’s API URL.

Step 2: Store the API key as a secret

-- Paste the real key value directly in Snowsight.
-- Never paste it into a chat window or AI assistant.
CREATE OR REPLACE SECRET POSTHOG.PUBLIC.POSTHOG_API_KEY
  TYPE = GENERIC_STRING
  SECRET_STRING = '<paste the key value here>';

Step 3: Create an external access integration

CREATE OR REPLACE EXTERNAL ACCESS INTEGRATION POSTHOG_INTEGRATION
  ALLOWED_NETWORK_RULES = (POSTHOG.PUBLIC.POSTHOG_NETWORK_RULE)
  ALLOWED_AUTHENTICATION_SECRETS = (POSTHOG.PUBLIC.POSTHOG_API_KEY)
  ENABLED = TRUE;

Step 4: Create a schema for the landed data

CREATE SCHEMA IF NOT EXISTS POSTHOG.GOOGLE_SEARCH_CONSOLE;

You don’t define any tables by hand. The procedure in Step 5 creates one table per PostHog table it pulls, with column names taken from PostHog’s actual response.

Tip: for a quick first test, you could store the whole response as a single VARIANT value just to confirm the round trip works. JSON blobs are awkward to query, though (nobody wants to write WHERE clicks > 50 against JSON), so the procedure below creates real columns automatically.

Step 5: Create the stored procedure that pulls every table

CREATE OR REPLACE PROCEDURE POSTHOG.GOOGLE_SEARCH_CONSOLE.PULL_ALL_SEARCH_CONSOLE_TABLES()
RETURNS VARCHAR
LANGUAGE PYTHON
RUNTIME_VERSION = '3.10'
PACKAGES = ('snowflake-snowpark-python', 'requests')
HANDLER = 'main'
EXTERNAL_ACCESS_INTEGRATIONS = (POSTHOG_INTEGRATION)
SECRETS = ('posthog_api_key' = POSTHOG.PUBLIC.POSTHOG_API_KEY)
EXECUTE AS OWNER
AS
$$
import _snowflake
import requests
import datetime
import json

POSTHOG_PROJECT_ID = "<your project id>"
HOGQL_SCHEMA = "googlesearchconsole"
TARGET_SCHEMA = "POSTHOG.GOOGLE_SEARCH_CONSOLE"

# PostHog limits for queries made with a personal API key:
#   - no LIMIT  -> only 100 rows come back
#   - OFFSET    -> rejected outright, even OFFSET 0
#   - any LIMIT -> at most 50,000 rows per request
# So small tables are read in one request, and large tables are
# read in date windows (keyset pagination on the "date" column).
ROW_CAP = 50000          # PostHog's hard per-request cap
SAFE_THRESHOLD = 40000   # tables up to this size go in one request
WINDOW_DAYS = 14         # date window size for large tables

# Every table PostHog's warehouse sidebar lists for this source.
# Check the sidebar yourself before reusing this -- table names are
# not derivable from the source's product name.
TABLE_NAMES = [
    "search_analytics_by_date",
    "search_analytics_by_country",
    "search_analytics_by_device",
    "search_analytics_by_page",
    "search_analytics_by_query",
    "search_analytics_by_query_page",
    "search_analytics_by_search_appearance",
]

def _hogql(url, headers, query):
    body = {"query": {"kind": "HogQLQuery", "query": query}}
    r = requests.post(url, headers=headers, json=body, timeout=120)
    if r.status_code != 200:
        raise RuntimeError(f"{r.status_code} - {r.text[:300]}")
    # Response shape: {"columns": [...], "results": [[...], ...], ...}
    return json.loads(r.text)

def _pull_one_table(session, token, table_name):
    url = f"https://us.posthog.com/api/projects/{POSTHOG_PROJECT_ID}/query/"
    headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}

    # 1. How many rows should land?
    count_payload = _hogql(url, headers, f"SELECT count(*) FROM {HOGQL_SCHEMA}.{table_name}")
    total = count_payload.get("results", [[0]])[0][0]

    columns = None
    all_rows = []

    if total <= SAFE_THRESHOLD:
        # 2a. Small table: one request with an explicit LIMIT
        payload = _hogql(url, headers, f"SELECT * FROM {HOGQL_SCHEMA}.{table_name} LIMIT {ROW_CAP}")
        columns = payload.get("columns") or []
        all_rows = payload.get("results") or []
    else:
        # 2b. Large table: walk the date range in WINDOW_DAYS windows
        range_payload = _hogql(url, headers, f"SELECT min(date), max(date) FROM {HOGQL_SCHEMA}.{table_name}")
        min_d, max_d = range_payload["results"][0]
        start = datetime.date.fromisoformat(str(min_d)[:10])
        end = datetime.date.fromisoformat(str(max_d)[:10])

        cur = start
        while cur <= end:
            win_end = cur + datetime.timedelta(days=WINDOW_DAYS)
            q = (f"SELECT * FROM {HOGQL_SCHEMA}.{table_name} "
                 f"WHERE date >= toDate('{cur.isoformat()}') AND date < toDate('{win_end.isoformat()}') "
                 f"LIMIT {ROW_CAP}")
            payload = _hogql(url, headers, q)
            if columns is None:
                columns = payload.get("columns") or []
            all_rows.extend(payload.get("results") or [])
            cur = win_end

    if not columns:
        return f"{table_name}: no columns returned, skipped"

    # 3. Build the table from the columns PostHog actually returned,
    #    then full refresh: truncate and reload
    target_table = f"{TARGET_SCHEMA}.{table_name.upper()}"
    col_defs = ", ".join([f'"{c.upper()}" VARCHAR' for c in columns])
    session.sql(f'CREATE TABLE IF NOT EXISTS {target_table} ({col_defs}, "LOADED_AT" TIMESTAMP_NTZ)').collect()
    session.sql(f'TRUNCATE TABLE {target_table}').collect()

    if not all_rows:
        return f"{table_name}: 0 rows available (expected {total})"

    now = datetime.datetime.utcnow()
    col_names = [c.upper() for c in columns] + ["LOADED_AT"]
    rows = [[None if v is None else str(v) for v in r] + [now] for r in all_rows]

    df = session.create_dataframe(rows, schema=col_names)
    df.write.mode("append").save_as_table(target_table)

    # 4. Flag any gap between what landed and what PostHog counted
    mismatch = f" -- MISMATCH: expected {total}" if len(rows) != total else ""
    return f"{table_name}: {len(rows)} rows -> {target_table}{mismatch}"

def main(session):
    token = _snowflake.get_generic_secret_string("posthog_api_key")
    summary = []
    for t in TABLE_NAMES:
        try:
            summary.append(_pull_one_table(session, token, t))
        except Exception as e:
            summary.append(f"{t}: FAILED - {e}")
    return "\n".join(summary)
$$;

Why every column is VARCHAR: this is deliberate. PostHog’s response doesn’t always give every column a clean, consistent type, and one wrong type guess can fail the whole load. When a query needs to compute with a column, it can cast it with TRY_TO_NUMBER() or TRY_TO_DATE(). That small, visible cost is better than a load that suddenly breaks weeks later because one row didn’t fit the guessed type.

Why it reads in date windows: PostHog’s query API has three limits for queries made with a personal API key. A query with no LIMIT returns only 100 rows. OFFSET is rejected outright, even OFFSET 0, so ordinary LIMIT/OFFSET paging doesn’t work. And a single request returns at most 50,000 rows, whatever LIMIT you ask for. The procedure therefore counts each table first. Tables with up to 40,000 rows are read in one request with an explicit LIMIT. Larger tables are read in 14-day windows on the date column (keyset pagination), each small enough to stay under the cap. Finally it compares the rows it loaded with PostHog’s count and flags any mismatch in the output.

Why a full refresh: each run truncates and reloads every table instead of appending. For a daily snapshot of reporting data, this is simpler and safer than a merge: there’s no risk of partial-day duplicates, and no merge key to get wrong.

What each daily run fetches: everything PostHog currently holds for each table, not only the newest day. If PostHog has five days of data on day 5, the run reloads days 1–5. On day 6 it reloads days 1–6: days 1–5 again, plus day 6. Because every table is truncated first, nothing is ever duplicated, and late revisions to earlier days (Search Console data usually lags two to three days) are picked up automatically. The flip side is that Snowflake mirrors PostHog: if PostHog stops keeping older days, they disappear from Snowflake on the next run too.

Step 6: Test it before you schedule it

CALL POSTHOG.GOOGLE_SEARCH_CONSOLE.PULL_ALL_SEARCH_CONSOLE_TABLES();

A successful run returns one line per table:

search_analytics_by_date: <n> rows -> POSTHOG.GOOGLE_SEARCH_CONSOLE.SEARCH_ANALYTICS_BY_DATE
search_analytics_by_country: <n> rows -> POSTHOG.GOOGLE_SEARCH_CONSOLE.SEARCH_ANALYTICS_BY_COUNTRY
search_analytics_by_device: <n> rows -> POSTHOG.GOOGLE_SEARCH_CONSOLE.SEARCH_ANALYTICS_BY_DEVICE
search_analytics_by_page: <n> rows -> POSTHOG.GOOGLE_SEARCH_CONSOLE.SEARCH_ANALYTICS_BY_PAGE
search_analytics_by_query: <n> rows -> POSTHOG.GOOGLE_SEARCH_CONSOLE.SEARCH_ANALYTICS_BY_QUERY
search_analytics_by_query_page: <n> rows -> POSTHOG.GOOGLE_SEARCH_CONSOLE.SEARCH_ANALYTICS_BY_QUERY_PAGE
search_analytics_by_search_appearance: <n> rows -> POSTHOG.GOOGLE_SEARCH_CONSOLE.SEARCH_ANALYTICS_BY_SEARCH_APPEARANCE

Each <n> should match the table’s row count in PostHog. If a line ends with -- MISMATCH: expected N, the number of rows that landed in Snowflake doesn’t match the count PostHog reports. See Troubleshooting.

Then query one of the tables, for example SELECT * FROM POSTHOG.GOOGLE_SEARCH_CONSOLE.SEARCH_ANALYTICS_BY_DATE. You should see real columns (CTR, DATE, CLICKS, POSITION, IMPRESSIONS) with values that match what PostHog’s own SQL editor shows for the same table.

Step 7: Schedule it

CREATE OR REPLACE TASK POSTHOG.GOOGLE_SEARCH_CONSOLE.DAILY_PULL_TASK
  WAREHOUSE = POSTHOG_WH
  SCHEDULE = 'USING CRON 0 6 * * * America/Los_Angeles'
AS
  CALL POSTHOG.GOOGLE_SEARCH_CONSOLE.PULL_ALL_SEARCH_CONSOLE_TABLES();

ALTER TASK POSTHOG.GOOGLE_SEARCH_CONSOLE.DAILY_PULL_TASK RESUME;

Don’t skip RESUME. Snowflake creates every new task in a suspended state. The task won’t run until you resume it.

Troubleshooting

  • Every call returns a permissions error: the PostHog API key is missing the Query: Read scope. Add the scope in PostHog, then update the Snowflake secret if you created a new key.
  • A table returns a query error: the table name doesn’t exist in that PostHog project. Copy the exact names from PostHog’s Data Warehouse sidebar into TABLE_NAMES.
  • Outbound requests are blocked: the network rule host doesn’t match your PostHog region. Use us.posthog.com for US Cloud or eu.posthog.com for EU Cloud in both the network rule and the procedure.
  • Every table loads exactly 100 or exactly 50,000 rows, or a line ends with MISMATCH: the pull is being cut off by one of PostHog’s row limits. Exactly 100 means a query ran without a LIMIT; exactly 50,000 means a single request hit PostHog’s per-request cap. Make sure you’re using the procedure from Step 5. If a MISMATCH persists on a large table, one 14-day window holds more than 50,000 rows: lower WINDOW_DAYS (for example, to 7) and run the procedure again. A small mismatch can also come from PostHog syncing new rows between the count and the pull; rerunning clears it.
  • The error says OFFSET is not supported: you’re running an older version of the procedure that pages with LIMIT/OFFSET. PostHog rejects OFFSET for queries made with a personal API key. Replace it with the date-window procedure from Step 5.
  • The task never runs: it is still suspended. Run ALTER TASK … RESUME and confirm its state with SHOW TASKS.

Limitations

  • Every column is text. Columns such as CLICKS and IMPRESSIONS land as VARCHAR, not NUMBER or DATE. This keeps loads reliable, but dashboards and dbt models built on top should cast what they need with TRY_TO_NUMBER or TRY_TO_DATE.
  • Full refresh, no history. Each run replaces yesterday’s data. If you need trends over time, add a snapshot table fed from these tables rather than changing this procedure.
  • Large tables take more requests. Each 14-day window is a separate API call, so the number of calls grows with the date range, and every row is held in memory before it’s written. This is fine for reporting tables like Search Console. For tables with millions of rows, switch to an incremental pull of the last few days merged on a key.
  • A failed run can leave a table empty. Each table is truncated before the new rows are inserted, and the two steps aren’t one transaction. If the insert fails, that table stays empty until the next successful run. Loading into a staging table and swapping it in with ALTER TABLE … SWAP WITH closes that gap.
  • Large tables need a date column. Only tables over 40,000 rows use the date-window path, and that path filters on date. The large Search Console tables have one. If you reuse this for a source whose large tables don’t, the run reports FAILED for that table rather than loading it partially.
  • One source per procedure. This example pulls the seven Google Search Console tables. To pull Google Ads, Meta Ads, TikTok Ads, or another connected source, change HOGQL_SCHEMA and TABLE_NAMES and keep everything else the same.

Reusing this setup for another PostHog project

Only four things change per project. Everything else in Steps 1–7 can be copied as is:

  • Snowflake account: run the setup in the target account.
  • PostHog project ID: set POSTHOG_PROJECT_ID in Step 5. You’ll find the ID in the project’s PostHog URL.
  • PostHog API key: in Steps 0 and 2, use a fresh key for that project with the Query: Read scope.
  • HogQL schema and table names: in Steps 4 and 5, confirm the real table names in PostHog’s Data Warehouse sidebar first.