# PostgreSQL Database Extractor (`parseforge/postgresql-database-extractor`) Actor

Extracts data from PostgreSQL databases. Connects via connection string or individual credentials, supports SSL, table selection, and row limits. Returns each row as a flat JSON object.

- **URL**: https://apify.com/parseforge/postgresql-database-extractor.md
- **Developed by:** [ParseForge](https://apify.com/parseforge) (community)
- **Categories:** Automation, Other, Developer tools
- **Stats:** 1 total users, 0 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: 5.00 out of 5 stars

## Pricing

Pay per event

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

[![ParseForge](https://raw.githubusercontent.com/ParseForge/apify-assets/main/banner.jpg)](https://apify.com/parseforge?fpr=vmoqkp)

### PostgreSQL Database Extractor

**Extract data from any PostgreSQL database into clean, flat datasets.** Connect with a connection string or individual credentials, select specific tables, and export to CSV, JSON, Excel, or XML. No complex setup, no API limits.

PostgreSQL databases hold critical business data, but moving that data into analytics tools or spreadsheets often means writing custom scripts or dealing with complex ETL pipelines. This Actor connects directly to your PostgreSQL instance, reads the tables you specify, and returns each row as a structured record. It works with self-hosted and cloud databases, supports SSL, and lets you filter tables and limit rows per table.

| Who uses it | What they scrape PostgreSQL for |
|---|---|
| Data analysts | Pull database tables into CSV or JSON for analysis in Excel, Python, or BI tools. |
| Developers | Automate database backups or sync data to other systems without writing custom code. |
| Business intelligence teams | Extract operational data from PostgreSQL into data warehouses or reporting platforms. |
| Data engineers | Set up scheduled extractions from production databases to feed downstream pipelines. |

### What it does

This Actor connects to a PostgreSQL database, extracts rows from selected tables, and returns each row as a flat JSON object.

- 🔌 **Flexible connection:** Use a full connection string or provide host, port, database, username, and password separately.
- 🔒 **SSL support:** Enable SSL to connect securely to cloud databases like AWS RDS, Google Cloud SQL, or Azure Database for PostgreSQL.
- 📋 **Table selection:** Specify exact tables to extract, exclude unwanted tables, or extract all tables by default.
- 📏 **Row limits:** Cap the number of rows per table to avoid huge extractions or sample data quickly.

Results export to CSV, JSON, Excel, or XML, or straight from the API.

### What you can do with PostgreSQL data

**📊 Export tables for analysis.**

A data analyst connects to the company PostgreSQL database, selects the sales and customers tables, and exports them to CSV for pivot tables in Excel.

**🔄 Sync data to another system.**

A developer schedules the Actor to extract new orders from PostgreSQL every hour and feed them into a CRM or data warehouse.

**🗄️ Create database backups.**

An operations team runs the Actor daily to dump all tables from a production database into JSON files stored in Apify's dataset.

**🧪 Sample data for testing.**

A QA engineer extracts the first 100 rows from each table to create a realistic test dataset without copying the entire database.

### Why choose this scraper

|  | What you get |
|---|---|
| **Direct database access** | Connect to any PostgreSQL instance with standard credentials or a connection string. |
| **Structured output** | Each table row becomes a flat JSON object, ready for export to CSV, JSON, Excel, or XML. |
| **Selective extraction** | Choose specific tables, exclude others, and limit rows to keep datasets manageable. |
| **Cloud-ready** | SSL support ensures secure connections to managed PostgreSQL services. |

### How it compares

No other Store actor targets PostgreSQL the same way, so the honest comparison is with the alternatives teams actually weigh.

| | PostgreSQL Database Extractor | Build it in-house | By hand |
|---|---|---|---|
| Setup | Run it now, zero config | Days of engineering | None, but hours per pull |
| When PostgreSQL changes | Maintained for you | You fix it | You re-learn the page |
| Proxies, retries, anti-bot | Built in | Your problem | Browser only |
| Output | Fixed JSON schema, CSV/Excel export | Whatever you build | Copy-paste |
| Cost | Pay per result | Engineering time | Analyst hours |

### Configure the run

Provide connection details, optionally list tables to include or exclude, and set a maximum row count per table. The Actor reads only the data you request and returns it in a consistent schema. The Input tab lists every parameter.

A first run with the defaults:

```json
{
  "host": "localhost",
  "port": 5432,
  "database": "mydb",
  "username": "user",
  "password": "password",
  "tables": [],
  "excludeTables": [],
  "maxRowsPerTable": 100
}
```

### Pricing

Pay-per-result: **$0.008 per result** collected. You pay only for the results written to your dataset.

| Results collected | Approximate cost |
|---|---|
| 100 results | $0.80 |
| 1,000 results | $8.00 |
| 10,000 results | $80.00 |

New Apify accounts start with $5 in free credit.

### Free users

Free-plan runs return up to 10 results as a preview. [Upgrade your Apify plan](https://console.apify.com/sign-up?fpr=vmoqkp) to collect up to 1,000,000 results per run.

### Run it

1. [Create a free Apify account with $5 in credit](https://console.apify.com/sign-up?fpr=vmoqkp).
2. Open the [PostgreSQL Database Extractor](https://apify.com/parseforge/postgresql-database-extractor?fpr=vmoqkp).
3. Set your inputs and any filters, then click **Start**.
4. Export the results as CSV, Excel, JSON, or XML from the **Dataset** tab.

Run it programmatically through the [Apify API](https://docs.apify.com/api/v2) (`run-sync-get-dataset-items`) or the [ApifyClient](https://docs.apify.com/api/client/js) for JavaScript and Python.

### Use with AI agents (MCP)

Give an AI agent live access to PostgreSQL through the Model Context Protocol. Add the Actor to Claude, Cursor, or any MCP client:

```bash
claude mcp add --transport http apify "https://mcp.apify.com/?tools=parseforge/postgresql-database-extractor"
```

Then prompt it in plain language to run the scraper and read back the results.

### Troubleshooting

**Why am I getting a connection error?**

Check that the host, port, database, username, and password are correct. If connecting to a cloud database, ensure SSL is enabled and that your IP is allowed in the database's firewall rules.

**Why are some tables not extracted?**

Verify the table names in your 'Tables to Extract' list, including the schema prefix. Also check that your database user has SELECT permission on those tables.

**Why is the run taking a long time?**

Large tables can slow down extraction. Set a 'Max Rows Per Table' limit to sample data, or exclude large tables you don't need.

**Why do I get an SSL error?**

Some PostgreSQL servers require SSL. Enable the 'Use SSL' option in the input. If the server uses a self-signed certificate, you may need to adjust the connection string with sslmode=require.

**Why is my password not working?**

Ensure there are no leading or trailing spaces in the password field. If your password contains special characters, try using a connection string instead of separate fields.

### FAQ

| Question | Answer |
|---|---|
| How do I connect to my PostgreSQL database? | You can provide a full connection string like postgresql://user:password@host:port/database, or enter the host, port, database, username, and password separately. If a connection string is provided, the other fields are ignored. |
| Does this work with cloud databases like AWS RDS or Google Cloud SQL? | Yes. Enable the SSL option in the input to establish a secure connection to most managed PostgreSQL services. |
| Can I extract only certain tables? | Yes. Use the 'Tables to Extract' field to list specific tables, or use 'Tables to Exclude' to skip unwanted tables. If neither is provided, all tables are extracted. |
| How do I limit the number of rows extracted? | Set the 'Max Rows Per Table' field to a positive integer. The Actor will extract up to that many rows from each table. If left empty, all rows are extracted. |
| What format is the output data in? | The Actor returns each table row as a flat JSON object. You can export the dataset to CSV, JSON, Excel, or XML from the Apify platform. |
| Is my database password stored securely? | Yes. All input fields, including passwords, are encrypted at rest and in transit by Apify. The password is only used to establish the connection during the run. |
| Can I schedule this Actor to run automatically? | Yes. You can set up a schedule in Apify to run the Actor at regular intervals, such as daily or hourly, to keep your extracted data up to date. |
| What happens if a table has no rows? | The Actor will return an empty array for that table. The run will still succeed, and other tables will be extracted normally. |
| Does this Actor modify my database? | No. It only performs SELECT queries to read data. It does not insert, update, or delete any records. |
| Can I extract data from a specific schema? | Yes. When listing tables, include the schema name, such as 'public.users' or 'sales.orders'. If you omit the schema, the default 'public' schema is assumed. |

### Related actors

Browse the full [ParseForge collection](https://apify.com/parseforge?fpr=vmoqkp) for more scrapers.

🆘 **Need help?** Email parseforge@protonmail.com with your run ID, your input, and what you expected.

⚠️ **Disclaimer.** This Actor is unofficial and is not affiliated with, endorsed by, or sponsored by PostgreSQL Global Development Group. It collects only publicly available data. You are responsible for using the collected data in compliance with the source's terms of service and applicable data-protection laws, including GDPR, CCPA, and PIPL. Do not use it to collect personal data unlawfully.

# Actor input Schema

## `connectionString` (type: `string`):

PostgreSQL connection string (e.g., postgresql://user:password@host:port/database). If provided, other connection parameters will be ignored.

## `host` (type: `string`):

PostgreSQL server hostname or IP address

## `port` (type: `integer`):

PostgreSQL server port (default: 5432)

## `database` (type: `string`):

Database name to connect to

## `username` (type: `string`):

PostgreSQL username

## `password` (type: `string`):

PostgreSQL password

## `ssl` (type: `boolean`):

Enable SSL connection (required for most cloud databases)

## `tables` (type: `array`):

List of specific tables to extract (e.g., \['public.users', 'public.orders']). If not provided, all tables will be extracted.

## `excludeTables` (type: `array`):

List of tables to exclude from extraction (e.g., \['public.logs', 'public.temp\_data'])

## `maxRowsPerTable` (type: `integer`):

Maximum number of rows to extract from each table. If not specified, all rows will be extracted.

## Actor input object example

```json
{
  "host": "localhost",
  "port": 5432,
  "database": "mydb",
  "username": "user",
  "password": "password",
  "tables": [],
  "excludeTables": [],
  "maxRowsPerTable": 100
}
```

# Actor output Schema

## `overview` (type: `string`):

Overview view of tables with key fields displayed in a table format

## `tables` (type: `string`):

Complete table dataset with all fields including table name, column information, extraction metadata, and dataset URLs

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "host": "localhost",
    "port": 5432,
    "database": "mydb",
    "username": "user",
    "password": "password",
    "tables": [],
    "excludeTables": [],
    "maxRowsPerTable": 100
};

// Run the Actor and wait for it to finish
const run = await client.actor("parseforge/postgresql-database-extractor").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "host": "localhost",
    "port": 5432,
    "database": "mydb",
    "username": "user",
    "password": "password",
    "tables": [],
    "excludeTables": [],
    "maxRowsPerTable": 100,
}

# Run the Actor and wait for it to finish
run = client.actor("parseforge/postgresql-database-extractor").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "host": "localhost",
  "port": 5432,
  "database": "mydb",
  "username": "user",
  "password": "password",
  "tables": [],
  "excludeTables": [],
  "maxRowsPerTable": 100
}' |
apify call parseforge/postgresql-database-extractor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,parseforge/postgresql-database-extractor"
        }
    }
}

```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/06iDmkvBpJnl8TEmp/builds/cfmTS74DhgBfPMkKY/openapi.json
