> ## Documentation Index
> Fetch the complete documentation index at: https://deepline.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Query a database | Agent guide

> Query your org Database securely through the Deepline API or SDK, without exposing a PostgreSQL connection string.

[Human guide: task steps and agent prompt →](https://deepline.com/docs/human/database-access.md)

For an application or agent, query the Database through the Deepline API. Your
Deepline API key selects the org. The API runs one bounded SQL statement
against that org's Database. You do not need to expose a PostgreSQL
connection string.

Use a direct PostgreSQL URI only when a database-native tool, such as BI or
`psql`, genuinely needs one.

## Query the API securely

Send the request from your server, worker, or trusted agent runtime. Keep
`DEEPLINE_API_KEY` in server-side secret storage. Never put it in a browser
application or commit it to source control.

```bash theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
curl --fail-with-body -sS -X POST https://code.deepline.com/api/v2/db/query \
  -H "Authorization: Bearer $DEEPLINE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "sql": "SELECT domain, company_name FROM enrichments.companies ORDER BY updated_at DESC LIMIT 20",
    "max_rows": 20
  }'
```

> [!TIP]
>
> A successful response returns `rows`, `columns`, `row_count_returned`, and
> `truncated`. An empty `rows` array means the query ran but found no matches.

The API accepts one SQL statement and up to 1,000 returned rows per request.
Use `max_rows` to bound the result you need. Inspect returned columns, row count
and `truncated` before interpreting the answer. Test writes only in permitted
customer-owned objects.

## Use the SDK

The SDK uses the same API boundary:

```ts theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
import { DeeplineClient } from 'deepline';

const client = new DeeplineClient({
  apiKey: process.env.DEEPLINE_API_KEY,
});

const result = await client.db.query({
  sql: 'SELECT domain, company_name FROM enrichments.companies ORDER BY updated_at DESC LIMIT 20',
  maxRows: 20,
});
```

## Query rules

| Operation | Where it is allowed |
| - | - |
| Read a managed Database view | `SELECT`, `EXPLAIN`, read-only `WITH`, and aggregates |
| Create or change agent-owned data | Qualified `storage.<table>` or an allowed customer-managed schema |
| Change Deepline-managed data | Never through this API |

For example, an agent or application can create its own scratch table:

```sql theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
CREATE TABLE IF NOT EXISTS storage.agent_notes (
  id text PRIMARY KEY,
  note text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);
```

These statements are intentionally blocked:

```sql theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
CREATE TABLE agent_notes (...);
DELETE FROM enrichments.companies WHERE domain = 'example.com';
```

Customer-managed schemas can also be created and used through this API, for
example `CREATE SCHEMA tenant_custom`, followed by a separate qualified
`CREATE TABLE tenant_custom.agent_notes (...)` statement. Reserved names and
internal objects remain protected. See the [Database contract](https://deepline.com/docs/features/postgresql-database.md).

## Keep the boundary safe

* Build fixed, allowlisted queries in trusted server-side code. Validate request
  values and constrain permitted tables, columns and filters. Do not forward
  arbitrary end-user SQL.
* Set `max_rows` and select only the columns your caller needs.
* Use the Database for working state. Write approved outcomes to your CRM. See
  [Database](https://deepline.com/docs/data-lifecycle.md).

## Direct PostgreSQL access

Use a Database URI only for a database-native application or BI tool. Obtain
it from the dashboard's Database Access flow, store it in server-side secret
storage, and write only to permitted customer storage objects. An owner or admin
must use a dashboard session to reveal the URI. Provisioning and password
rotation are also dashboard/admin-session controls, separate from the public
query API.

## Query an external Postgres database

A connected Postgres database belongs to your own database provider. It uses
`postgres_run_query` and saved integration credentials, separate from the
Deepline Database API and its managed-schema rules above. Follow the
[external Postgres credential instructions](https://deepline.com/docs/features/bring-your-own-keys.md#external-postgres),
including Supabase Session Pooler setup when needed.

The tool accepts one statement with positional `binds`, `timeoutMs`, and
`rowLimit`. Reads run in a read-only transaction; mutations and DDL execute
directly without a `write` opt-in. Use a read-only database role when writes
must be prohibited, and authorize external changes separately.

> [accordion] Inspect external tables, foreign keys, and a bounded join
>
> List user tables with the local Deepline CLI:
>
> ```bash theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
> deepline run postgres_run_query --input '{
>   "query": "SELECT table_schema, table_name FROM information_schema.tables WHERE table_type = '\''BASE TABLE'\'' AND table_schema NOT IN ('\''pg_catalog'\'', '\''information_schema'\'') ORDER BY table_schema, table_name",
>   "rowLimit": 200,
>   "timeoutMs": 30000
> }'
> ```
>
> Inspect declared foreign keys before choosing a join. Pair the source and target
> columns by constraint position, including composite keys:
>
> ```sql theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
> SELECT
>   source_ns.nspname AS table_schema,
>   source_table.relname AS table_name,
>   source_column.attname AS column_name,
>   target_ns.nspname AS foreign_table_schema,
>   target_table.relname AS foreign_table_name,
>   target_column.attname AS foreign_column_name
> FROM pg_catalog.pg_constraint fk
> JOIN pg_catalog.pg_class source_table ON source_table.oid = fk.conrelid
> JOIN pg_catalog.pg_namespace source_ns ON source_ns.oid = source_table.relnamespace
> JOIN pg_catalog.pg_class target_table ON target_table.oid = fk.confrelid
> JOIN pg_catalog.pg_namespace target_ns ON target_ns.oid = target_table.relnamespace
> CROSS JOIN LATERAL unnest(fk.conkey, fk.confkey) AS key_columns(source_num, target_num)
> JOIN pg_catalog.pg_attribute source_column
>   ON source_column.attrelid = fk.conrelid
>  AND source_column.attnum = key_columns.source_num
> JOIN pg_catalog.pg_attribute target_column
>   ON target_column.attrelid = fk.confrelid
>  AND target_column.attnum = key_columns.target_num
> WHERE fk.contype = 'f'
> ORDER BY table_schema, table_name, source_column.attnum;
> ```
>
> For example, a Supabase project containing the PostgreSQL DVD Rental sample
> schema can join actors to films through `film_actor`:
>
> ```bash theme={"languages":{"custom":["/languages/deepline-prompt.json"]}}
> deepline run postgres_run_query --input '{
>   "query": "SELECT a.actor_id, a.first_name, a.last_name, f.film_id, f.title, f.release_year FROM public.film_actor fa JOIN public.actor a ON a.actor_id = fa.actor_id JOIN public.film f ON f.film_id = fa.film_id ORDER BY a.actor_id, f.film_id LIMIT 10",
>   "rowLimit": 10,
>   "timeoutMs": 30000
> }'
> ```
>
> The response includes `data.rows`, `data.rowCount`, `data.columns`, the command
> tag, and non-secret connection metadata such as the host, database, and schema.
>
> Use positional `$1`, `$2` placeholders with `binds` for variable values, rather
> than interpolating them into SQL. Bound reads with both SQL `LIMIT` and
> `rowLimit`; inspect `data.limited` along with the returned count and columns.
> The examples use the DVD Rental schema only where that sample is installed;
> inspect your actual schema before choosing tables or joins.

> [card] [SDK API reference](https://deepline.com/docs/api-reference.md)
>
> See the supported `POST /api/v2/db/query` contract and SDK method.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.