> For the complete documentation index, see [llms.txt](https://docs.coupler.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.coupler.io/sources/category/files-and-tables/postgresql.md).

# PostgreSQL

Export PostgreSQL tables, views, and custom SQL queries to Google Sheets, BigQuery, Excel, and AI tools via Coupler.io — automate reporting without code.

PostgreSQL is a powerful, open-source relational database. With Coupler.io, you can automatically export data from any PostgreSQL table, view, or custom SQL query to Google Sheets, Excel, BigQuery, Looker Studio, or AI destinations like Claude and ChatGPT — no code required.

## Why connect PostgreSQL to Coupler.io?

* **Automate reporting** — Stop manually exporting data. Set up a data flow once and refresh on a schedule.
* **Query flexibility** — Pull data from tables, views, or write custom SQL to get exactly what you need.
* **Multiple destinations** — Send PostgreSQL data to spreadsheets, data warehouses, BI tools, or AI models.
* **Real-time insights** — Keep dashboards and reports up-to-date without manual work.

## Prerequisites

Before you start, you'll need:

* **PostgreSQL database access** — Host, port, database name, username, and password.
* **Network access** — Your PostgreSQL instance must accept connections from Coupler.io's IP addresses (we'll provide these during setup).
* **Read permissions** — Your database user needs SELECT access to the tables or views you want to import.

## Quick start

{% hint style="success" %}
If your PostgreSQL database is behind a firewall, you'll need to whitelist Coupler.io's IP addresses before connecting. We'll show you which IPs to allow during the setup process.
{% endhint %}

## How to connect

{% stepper %}
{% step %}
**Create a new data flow.** Click "Create" and choose PostgreSQL as your source. Enter your database connection details:

* Host (e.g., `db.example.com`)
* Port (usually `5432`)
* Database name
* Username
* Password

Coupler.io will test the connection and show you our IP addresses that need to be whitelisted in your database firewall (if applicable).
{% endstep %}

{% step %}
**Choose your report type.** Select "Table or view" to pick an existing table or view, or "Custom SQL" to write a query that pulls the exact data you need.
{% endstep %}

{% step %}
**Pick your schema and table** (if using Table or view mode). If you're using Custom SQL, enter your SQL query — for example: `SELECT id, name, created_at FROM users WHERE status = 'active'`.
{% endstep %}

{% step %}
**Select your destination.** Choose where your data goes: Google Sheets, Excel, BigQuery, Looker Studio, or an AI destination like Claude or ChatGPT.
{% endstep %}

{% step %}
**Run the data flow.** Click "Run" to test the connection and import your data. Once it completes successfully, your data is ready in the destination.
{% endstep %}
{% endstepper %}

{% hint style="info" %}
After a successful manual run, you can schedule the data flow to refresh automatically (daily, weekly, or on a custom schedule).
{% endhint %}

## What you can import

| Option            | What it does                                                                   |
| ----------------- | ------------------------------------------------------------------------------ |
| **Table or view** | Select any table or view from your PostgreSQL database by schema and name.     |
| **Custom SQL**    | Write a SQL query to filter, join, aggregate, or transform data before import. |

## PostgreSQL data overview

PostgreSQL data flows pull data directly from your database using either table selection or custom SQL queries. The data structure depends on what you're importing.

## Import modes

| Mode              | Use case                                                          | Example                                                                        |
| ----------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| **Table or view** | Import all or most data from a single table or materialized view. | Pull the `customers` table as-is.                                              |
| **Custom SQL**    | Write a query to filter, join, aggregate, or transform data.      | `SELECT customer_id, COUNT(*) as order_count FROM orders GROUP BY customer_id` |

## Available columns and data types

When you import from PostgreSQL, all columns and their data types come through as-is. Common PostgreSQL data types include:

#### Numeric types

| Type                         | Description             |
| ---------------------------- | ----------------------- |
| `INTEGER`                    | Whole numbers           |
| `BIGINT`                     | Large whole numbers     |
| `DECIMAL` / `NUMERIC`        | Precise decimal numbers |
| `FLOAT` / `DOUBLE PRECISION` | Floating-point numbers  |

#### Text types

| Type               | Description          |
| ------------------ | -------------------- |
| `VARCHAR` / `TEXT` | Variable-length text |
| `CHAR`             | Fixed-length text    |

#### Date and time types

| Type                        | Description                              |
| --------------------------- | ---------------------------------------- |
| `DATE`                      | Calendar date                            |
| `TIME`                      | Time of day                              |
| `TIMESTAMP` / `TIMESTAMPTZ` | Date and time (with or without timezone) |

#### Other types

| Type             | Description                     |
| ---------------- | ------------------------------- |
| `BOOLEAN`        | True/False values               |
| `UUID`           | Unique identifiers              |
| `JSON` / `JSONB` | JSON objects (imported as text) |
| `ARRAY`          | Arrays (imported as text)       |

## Common query patterns

Here are useful SQL queries you can paste into the Custom SQL field:

**Filter by date range:**

```sql
SELECT * FROM orders 
WHERE created_at >= '2024-01-01' AND created_at < '2024-02-01'
```

**Aggregate data:**

```sql
SELECT user_id, COUNT(*) as order_count, SUM(total) as revenue 
FROM orders 
GROUP BY user_id
```

**Join multiple tables:**

```sql
SELECT c.name, o.order_id, o.total 
FROM customers c 
JOIN orders o ON c.id = o.customer_id 
WHERE o.created_at >= NOW() - INTERVAL '30 days'
```

## Use cases by role

{% tabs %}
{% tab title="Analysts" %}
Analysts use PostgreSQL data flows to build custom datasets for analysis. Write SQL queries to join tables, aggregate metrics, and filter to specific segments. Export to BigQuery for large-scale analysis or to Google Sheets for quick exploration. Use the Join transformation to combine PostgreSQL data with data from other sources (e.g., marketing platforms).
{% endtab %}

{% tab title="Finance teams" %}
Finance teams pull revenue, expense, and transaction data from PostgreSQL to Google Sheets or Excel for reconciliation and reporting. Use Custom SQL to aggregate by department, month, or cost center. Append data from multiple accounts or time periods using the Append transformation, then send to Data Studio for executive dashboards.
{% endtab %}

{% tab title="Product managers" %}
Product teams query user behavior, feature adoption, and event data from PostgreSQL. Write SQL to filter by cohort, feature flag, or date range. Send aggregated metrics to Data Studio or Claude (via Coupler.io) to generate insights and identify trends automatically.
{% endtab %}

{% tab title="Operations" %}
Ops teams use PostgreSQL data flows to monitor application health, sync customer or employee data, and automate status reporting. Pull from logs, events, or operational tables and send to Google Sheets for team dashboards. Use Custom SQL to filter errors, slow queries, or specific time windows.
{% endtab %}
{% endtabs %}

## Platform-specific notes

* **IP whitelisting required** — Coupler.io connects from fixed IP addresses. You must whitelist these in your PostgreSQL firewall or security group (AWS RDS, Azure Database, etc.).
* **Read-only access** — Your database user only needs SELECT permissions; no writes or schema changes.
* **Large result sets** — If your query returns millions of rows, consider filtering by date, aggregating, or using LIMIT to avoid timeouts.
* **Connection pooling** — PostgreSQL has a connection limit per role. If you run many data flows, you may hit this limit; consider using a connection pooler or increasing max\_connections.
* **Custom SQL performance** — Complex queries with multiple joins or aggregations may take longer. Test in psql or your query tool first.
* **JSON/ARRAY types** — These are imported as text strings. Parse them in your destination (Google Sheets formulas, BigQuery JSON functions, etc.) if needed.

## PostgreSQL common issues

### Connection issues

<details>

<summary>"Connection refused" or "No route to host" error</summary>

Your PostgreSQL database is not accepting connections from Coupler.io's IP addresses.

**Fix:**

1. Copy the IP addresses shown in the error message or connection dialog.
2. Add these IPs to your database firewall or security group:
   * **AWS RDS:** Edit the security group's inbound rules; add port 5432 for Coupler.io IPs.
   * **Azure Database:** Add firewall rules in the Azure portal.
   * **Self-hosted/On-premise:** Update `pg_hba.conf` or your network firewall to allow Coupler.io IPs on port 5432.
3. Test the connection again in Coupler.io.

If you're unsure how to whitelist IPs in your infrastructure, contact your database administrator or cloud provider support.

</details>

<details>

<summary>"Connection already closed" error</summary>

PostgreSQL closed the connection before the data flow completed, usually due to idle timeout or network instability.

**Fix:**

1. Check your PostgreSQL `idle_in_transaction_session_timeout` setting (default is no limit). If set to a low value, increase it.
2. If the query is slow, optimize it:
   * Add indexes to WHERE clause columns: `CREATE INDEX idx_name ON table(column);`
   * Filter by date range instead of pulling all historical data.
   * Use LIMIT to test: `SELECT * FROM table LIMIT 1000`.
3. Re-run the data flow.

</details>

<details>

<summary>"Connection is timing out" error</summary>

The database took too long to respond (usually > 30 seconds).

**Fix:**

1. **Test the query directly** in psql or a query tool to see how long it takes.
2. **Optimize the SQL query:**
   * Add a date range filter: `WHERE created_at >= NOW() - INTERVAL '90 days'`.
   * Use aggregation to reduce rows: `GROUP BY` instead of SELECT \*.
   * Add indexes: `CREATE INDEX idx_column ON table(column);`
3. **Check database load:** Ask your DBA if the database is under heavy load during your scheduled import time.
4. **Increase timeout** (if self-hosted): Adjust PostgreSQL's `statement_timeout` or Coupler.io's connection timeout.

</details>

<details>

<summary>"Authentication failed" error</summary>

Your username, password, or database name is incorrect.

**Fix:**

1. Double-check your credentials in the connection dialog.
2. Test the connection manually using psql: `psql -h hostname -U username -d database_name -p 5432`.
3. If the manual connection works, re-enter credentials in Coupler.io carefully (watch for trailing spaces).
4. If you recently changed your password, update it in Coupler.io.

</details>

### Missing data

<details>

<summary>No data appears after import, or only partial data</summary>

Your query may have no results, be filtered too strictly, or be missing tables/columns.

**Fix:**

1. **Test your query** directly in psql: `SELECT COUNT(*) FROM table;` to confirm data exists.
2. **Check schema and table names** — they're case-sensitive in PostgreSQL. Use `\dt` in psql to list tables.
3. **Verify column access** — ensure your database user has SELECT permissions: `GRANT SELECT ON table TO username;`
4. **Review filters** in your SQL query. If you're filtering by date, ensure the date range isn't too narrow.
5. **Check row limits** — if you used LIMIT in your query, increase or remove it.

</details>

<details>

<summary>Data is outdated or hasn't refreshed</summary>

The data flow hasn't run recently, or the destination wasn't updated.

**Fix:**

1. **Check the data flow status** — click on the data flow and review the run history. Did the last run succeed or fail?
2. **Check your schedule** — is the data flow scheduled to run? If not, it only runs when you manually trigger it.
3. **Run manually** — click "Run" to trigger an immediate refresh.
4. **Check the destination** — if using Google Sheets, ensure you're viewing the correct sheet and it's not cached. Refresh the browser.

</details>

### Permission errors

<details>

<summary>"Permission denied" or "role does not have SELECT privilege" error</summary>

Your database user lacks SELECT permissions on the table or schema.

**Fix:**

1. **Grant SELECT permission** (run as a superuser or table owner):

   ```sql
   GRANT SELECT ON table_name TO your_username;
   GRANT USAGE ON SCHEMA schema_name TO your_username;
   ```
2. **For all tables in a schema:**

   ```sql
   GRANT USAGE ON SCHEMA schema_name TO your_username;
   GRANT SELECT ON ALL TABLES IN SCHEMA schema_name TO your_username;
   ```
3. Re-test the connection in Coupler.io.

</details>

### Data discrepancies

<details>

<summary>Fewer rows in Coupler.io than in the database</summary>

Your query may be filtering out rows unintentionally, or you may be comparing counts from different queries.

**Fix:**

1. **Run the same query in psql** to confirm the row count: `SELECT COUNT(*) FROM table WHERE ... ;`
2. **Check for NULL values or filters** in your SQL that might exclude rows.
3. **Verify date ranges** — are you filtering by timestamp and comparing against a different timezone?
4. **Check for duplicates** — does your query have a JOIN that multiplies rows? Use DISTINCT if needed.

</details>

<details>

<summary>"Division by zero" or other SQL errors during import</summary>

Your SQL query has a logic error (e.g., dividing by a NULL or zero value, invalid type conversion).

**Fix:**

1. **Fix the SQL query** to handle edge cases:

   ```sql
   SELECT id, CASE WHEN denominator = 0 THEN 0 ELSE numerator / denominator END as ratio
   FROM table;
   ```
2. **Use COALESCE** to replace NULL values: `COALESCE(column, 0)`.
3. **Cast types explicitly** if mixing text and numbers: `CAST(column AS INTEGER)`.
4. Re-run the data flow.

</details>

### Rate limits and performance

<details>

<summary>"Too much data" error or memory limit exceeded</summary>

Your query returns too many rows or columns for the import to process in memory.

**Fix:**

1. **Add a WHERE clause** to filter by date, status, or category: `WHERE created_at >= NOW() - INTERVAL '90 days'`.
2. **Select only needed columns** instead of SELECT \*:

   ```sql
   SELECT id, name, email FROM users WHERE active = true;
   ```
3. **Aggregate the data** to reduce row count:

   ```sql
   SELECT DATE(created_at), COUNT(*) as count FROM events GROUP BY DATE(created_at);
   ```
4. **Split into multiple data flows** — import different date ranges or tables separately, then Append them in Coupler.io.

</details>

<details>

<summary>Data flow times out or runs very slowly</summary>

Your query is inefficient, the database is overloaded, or the network is slow.

**Fix:**

1. **Add indexes** to columns used in WHERE or JOIN clauses:

   ```sql
   CREATE INDEX idx_user_id ON orders(user_id);
   CREATE INDEX idx_created_at ON orders(created_at);
   ```
2. **Reduce data volume** — filter by date, use aggregation, or remove unnecessary JOINs.
3. **Schedule imports during off-peak hours** when the database is less loaded.
4. **Profile the query** using EXPLAIN ANALYZE in psql to identify slow parts.

</details>

## PostgreSQL FAQ

<details>

<summary>Do I need to whitelist IP addresses? Where do I find them?</summary>

Yes, if your PostgreSQL database is behind a firewall (AWS RDS, Azure, on-premise, etc.), you must whitelist Coupler.io's IP addresses. When you create a PostgreSQL connection in Coupler.io, the connection dialog displays the exact IPs to whitelist. Add these IPs to:

* **AWS RDS:** Modify the security group's inbound rules; add port 5432.
* **Azure:** Add firewall rules in the Azure portal.
* **Self-hosted/On-premise:** Update your network firewall or PostgreSQL's `pg_hba.conf` file.

Without whitelisting, you'll see "Connection refused" or "No route to host" errors.

</details>

<details>

<summary>Can I import from a Table or View, or do I need to write SQL?</summary>

You have two options:

1. **Table or View** — Select a schema and table name from a dropdown. Coupler.io imports all data from that table or view.
2. **Custom SQL** — Write a SQL query to filter, join, aggregate, or transform data before import.

Start with "Table or View" for simple imports. Use "Custom SQL" if you need filtering, joins, or aggregation.

</details>

<details>

<summary>What if my query is slow or times out?</summary>

If your data flow exceeds 30 seconds, Coupler.io will time out. To fix this:

1. **Add a date filter** to reduce rows: `WHERE created_at >= NOW() - INTERVAL '90 days'`
2. **Use aggregation** instead of SELECT \*: `SELECT user_id, COUNT(*) FROM orders GROUP BY user_id`
3. **Add indexes** to columns in your WHERE clause: `CREATE INDEX idx_created_at ON orders(created_at);`
4. **Remove unnecessary columns**: Select only what you need.

Test your query in psql first to see how long it takes. If it's slow there, optimize it before adding to Coupler.io.

</details>

<details>

<summary>Can I join data from PostgreSQL with data from other sources?</summary>

Yes! In Coupler.io, you can use the **Join** transformation to combine PostgreSQL data with data from other sources (Google Ads, Facebook Ads, Stripe, etc.). For example, join customer data from PostgreSQL with revenue data from Stripe on a common ID. You can also use the **Append** transformation to combine data from multiple PostgreSQL tables or data flows.

</details>

<details>

<summary>What permissions does my database user need?</summary>

Your database user needs SELECT permission on the tables or views you're importing. To grant this:

```sql
GRANT SELECT ON table_name TO username;
GRANT USAGE ON SCHEMA schema_name TO username;
```

Do NOT grant INSERT, UPDATE, DELETE, or DROP permissions. Coupler.io only reads data.

</details>

<details>

<summary>Can I schedule data flow refreshes automatically?</summary>

Yes! After your first successful manual run, you can schedule the data flow to refresh on a daily, weekly, or custom schedule. In the data flow settings, choose your refresh frequency. Coupler.io will automatically run the import at the scheduled time and update your destination (Google Sheets, BigQuery, etc.).

</details>

<details>

<summary>Why am I getting a "Too much data" error?</summary>

Your query returns too many rows or columns to import at once. To fix this:

1. **Filter by date**: `WHERE created_at >= NOW() - INTERVAL '30 days'`
2. **Select fewer columns**: Instead of SELECT \*, list specific columns.
3. **Aggregate data**: Use GROUP BY to reduce row count.
4. **Split into multiple flows**: Import different date ranges or tables separately, then Append them in Coupler.io.

Test your query in psql and check the row count: `SELECT COUNT(*) FROM table WHERE ...;`

</details>

<details>

<summary>Can I send PostgreSQL data to AI destinations like Claude or ChatGPT?</summary>

Yes! Coupler.io supports AI destinations including Claude, ChatGPT, Cursor, Gemini, Perplexity, and OpenClaw. Create a data flow that imports PostgreSQL data to an AI destination, and you can automatically generate insights, summaries, or reports from your database. For example, query weekly sales data from PostgreSQL and send it to Claude to generate a trend analysis.

</details>

<details>

<summary>What happens if my database password changes?</summary>

Your data flows will fail with an "Authentication failed" error. Update the password in the PostgreSQL connection settings:

1. In Coupler.io, go to **Connections** and find your PostgreSQL connection.
2. Click **Edit** and update the password.
3. Run a manual test to confirm the new credentials work.
4. Your scheduled data flows will resume on the next refresh.

</details>

<details>

<summary>Can I export data from multiple PostgreSQL databases in one data flow?</summary>

Each data flow has one primary source (one PostgreSQL database). However, you can create multiple data flows (one per database) and use the **Append** transformation to combine them into a single destination. For example, append sales data from PostgreSQL prod and PostgreSQL staging into one Google Sheet.

</details>

{% hint style="info" %}
For connection and IP whitelisting details, see the [Connection issues](#connection-issues) section. For performance optimization and slow query fixes, see [Performance optimization](https://docs.coupler.io/sources/category/files-and-tables/postgresql/best-practices.md#performance-optimization).
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.coupler.io/sources/category/files-and-tables/postgresql.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
