

# Query tables with ExecuteSql

 `ExecuteSql` runs one read-only SQL statement over the AWS Glue Data Catalog tables of one connection in an Agent context and returns typed columns and rows. Use it when you want to write the query yourself. The built-in query engine runs PostgreSQL-compatible SQL over tables in Amazon Simple Storage Service (Amazon S3), Amazon S3 Tables, and Apache Hive, within the connection’s scope. For how real-time queries relate to the ingested graph, see [AWS-native structured sources](aws-native-structured-sources.md).

 `ExecuteSql` reads AWS Glue Data Catalog connections only. To query Amazon Redshift, Amazon Relational Database Service (Amazon RDS), Amazon DynamoDB, Snowflake, or Databricks, use agentic retrieval. `ExecuteSql` is available in the AWS SDKs and as the MCP tool `context___ExecuteSql`.

## Prerequisites
<a name="executesql-prerequisites"></a>
+ A `GLUE_DATA_CATALOG` connection with the tables you want inside its scope. The identity that reads the connection, its data access role or the caller, needs permission to read the tables.
+ The `context:ExecuteSql` permission on the Agent context.
+ An active Agent context.

## SQL rules
<a name="executesql-sql-rules"></a>
+ Reference each table by its full AWS Glue table ARN in double quotation marks, for example `FROM "arn:aws:glue:us-east-1:111122223333:table/sales/orders"`. For Amazon S3 Tables, the ARN has the form `arn:aws:glue:region:account-id:table/s3tablescatalog/bucket/namespace/table`.
+ List every table the statement reads in `tableArnList` (1 to 10). AWS Context doesn’t parse your SQL to find tables. Each table must be in the Agent context’s AWS account and Region and inside the connection’s scope; otherwise the request fails with `ValidationException`. `ExecuteSql` can’t query a catalog in another account. To query data that another account shares with your Agent context, use agentic retrieval.
+ Quote every identifier. Unquoted identifiers are converted to uppercase and matching is case-sensitive, so unquoted `OrderDate` matches nothing.
+ Write one `SELECT` or `WITH` statement. Write keywords (including `INTO`), multiple statements, and SQL hints are rejected. Nonstandard string escapes (`E'…​'`, `$$…​$$`, `\'`) are also rejected. Double a quotation mark to escape it (`''`).

## To run a query (AWS CLI)
<a name="to-run-a-query-cli"></a>

The following request totals net revenue by Region. Replace the account ID, connection ID, and table ARN with your own values, save the request as `revenue-query.json`, and run it:

```json
{
  "agentContextId": "ac-1234567890abcdef",
  "connectionId": "conn-0123456789abcdef",
  "query": {
    "sql": {
      "statement": "SELECT \"region\", SUM(\"net_revenue\") AS \"revenue\" FROM \"arn:aws:glue:us-east-1:111122223333:table/sales/orders\" GROUP BY \"region\" ORDER BY \"revenue\" DESC LIMIT 100",
      "tableArnList": ["arn:aws:glue:us-east-1:111122223333:table/sales/orders"]
    }
  }
}
```

```bash
aws context execute-sql --cli-input-json file://revenue-query.json
```

## To run a query (AWS SDK for Python)
<a name="to-run-a-query-sdk-python"></a>

```python
import boto3

client = boto3.client("context", region_name="us-east-1")

response = client.execute_sql(
    agentContextId="ac-1234567890abcdef",
    connectionId="conn-0123456789abcdef",
    query={"sql": {
        "statement": 'SELECT "region", SUM("net_revenue") AS "revenue" '
                     'FROM "arn:aws:glue:us-east-1:111122223333:table/sales/orders" '
                     'GROUP BY "region" ORDER BY "revenue" DESC LIMIT 100',
        "tableArnList": ["arn:aws:glue:us-east-1:111122223333:table/sales/orders"],
    }},
)

print([c["name"] for c in response["columnMetadata"]])
for row in response["rows"]:
    print(row["values"])
```

## Read the response
<a name="executesql-read-the-response"></a>

The response is one page with `columnMetadata` and `rows`. `columnMetadata` has one entry per column, with its `name`, `type`, and `nullable`. Each row is a positional `values` list matching the columns. Each value sets exactly one member: `longValue`, `doubleValue`, `booleanValue`, `stringValue`, `blobValue`, `jsonValue`, or `nullValue`. `ARRAY`, `STRUCT`, and `MAP` columns come back as JSON text in `jsonValue`. `DECIMAL`, `DATE`, `TIME`, `TIMESTAMP`, and `NaN` or infinite doubles come back as text in `stringValue`. For the full value mapping, see `ExecuteSql` in the * AWS Context API Reference*.

## Limits
<a name="executesql-limits"></a>

A query returns at most 50,000 rows, cut without an error, so add your own `LIMIT` and treat a 50,000-row result as truncated. A result over 5 MiB fails rather than being trimmed; aggregate in SQL or select fewer columns. A query has 30 seconds to complete, and an account can run two `ExecuteSql` queries at a time; the queries the retrieval agent runs during agentic retrieval don’t count toward this limit. The query reads data with the connection’s data access role, or with the caller’s credentials if the connection has none, so AWS Lake Formation permissions on that identity apply; see [How access controls apply when AWS Context queries data](how-access-controls-apply-when-aws-context-queries-data.md).