The AI Said This Athena Query Was Cheaper. I Made It Prove It.
I let Amazon Bedrock propose a lower-scan Athena query, then made deterministic checks across Athena, EMR Serverless, Redshift Serverless, and Glue Data Quality decide whether it was safe. The result cut measured scan bytes by 78.3%—and still ran slightly slower.
I have seen plenty of demos where an AI model writes a better-looking SQL
query and the story ends there. That has never felt like enough to me. A query
can look clever, run successfully, and still return the wrong answer or cost
more than the one it replaced.
So I gave myself a stricter rule for this experiment: Bedrock could suggest an
optimization, but it could not approve or execute one. The final decision had
to come from ordinary code and measurements produced by AWS services.
The lab ended up using Amazon Bedrock, Amazon S3 Tables, Athena, EMR
Serverless, Redshift Serverless, AWS Glue Data Quality, and AWS Lake Formation.
The outcome was more interesting than a clean success story. The proposed
query returned the same values and scanned 78.3% fewer bytes in Athena, but it
was also slightly slower on my small test fixture.
I am glad it was. That awkward result forced the system to say exactly what
the evidence supported—less data scanned—and nothing more. I could not
honestly call the query faster or attach a made-up cost saving to it.
I have published the code, sanitized measurements, and article-safe evidence
in the
AI Lakehouse Query Lab repository
so you can inspect the parts that matter rather than take my word for it.

I started with a query that already worked
I was not trying to prove that Bedrock could turn a natural-language question
into SQL. There are already good examples of that pattern.
I started one step later. I already had a valid Athena query, and I wanted the
model to look at how it accessed the data and suggest an alternative that
might scan less:
SELECT category, ROUND(SUM(amount), 2) AS total_amountFROM "<S3_TABLES_CATALOG>"."lab"."events_raw"WHERE event_date = DATE '2026-11-01'GROUP BY categoryORDER BY category;For the test, I generated 10,000 rows and loaded the same data into two Apache
Iceberg tables:
-
events_raw, with no partitioning
-
events, partitioned byevent_date
The rows were identical; only the physical layout changed. That kept the
model's task intentionally simple. It could propose using the partitioned
table, while the validator took responsibility for the harder questions: Is
the SQL allowed? Does it return the same result? Does it actually scan less?
Can another engine reproduce the answer?
I kept the model away from the controls
The Bedrock request required tool-shaped output with exactly four fields:
{ "engine": "athena", "sql": "SELECT ...", "rationale": "Use the partitioned table for the date predicate.", "assumptions": [ "Both tables contain the same immutable validation rows." ]}The response then had to pass a Python gate whose rules did not care how
confident the model sounded:
- only
SELECTorWITH ... SELECT
- no comments or multiple statements
- no DDL or DML verbs
- allow-listed engines
- allow-listed table identifiers
- exact result hash and row-count comparison
- a configurable minimum scan reduction
The core decision function is deliberately unexciting:
def decide(baseline, candidate, minimum_savings_fraction=0.10): reasons = []
if candidate.result_hash != baseline.result_hash: reasons.append("result hashes differ")
if candidate.row_count != baseline.row_count: reasons.append("row counts differ")
savings = ( baseline.data_scanned_bytes - candidate.data_scanned_bytes ) / baseline.data_scanned_bytes
if savings < minimum_savings_fraction: reasons.append("scan savings are below the required threshold")
return not reasons, reasons, savingsThat is exactly what I wanted. No model score, rationale, or persuasive wording
can override those checks.
Three failures made the design better
The proposal did not sail through on the first attempt. In fact, the failures
became the most useful part of the build because each one exposed a boundary I
had assumed was stronger than it really was.
1. The guardrail blocked a legitimate optimization prompt
I initially set the Bedrock prompt-attack filter to high strength. The request
never reached the model. The filter treated my own strict instructions about
SQL behavior and output format as a prompt attack.
For this particular workload, it was a false positive. I changed the
prompt-attack strength to
LOW and kept the credential and password
protections in place.My takeaway was not “turn off the guardrail.” It was that guardrail settings
need to be tested with the prompts the application will really send. The
strictest setting is not useful if it blocks the intended engineering
workflow.
2. Free-form JSON was not actually a contract
The next response chose the right table, but wrapped the answer in Markdown
and returned
assumptions as a string instead of a list.I knew what it meant. The validator still rejected it.
That may sound pedantic, but “a person can work out what the model meant” is a
terrible contract for an automated system.
3. The first tool-use proposal invented an invalid identifier shape
Switching to tool use fixed the response-shape problem, but the first proposal
then combined the catalog, namespace, and table into one quoted identifier.
The SQL looked plausible at a glance, but Athena would not accept it.
The validator rejected the proposal and sent back one narrowly scoped repair
message: keep the three identifier components separately quoted.
4. One repair produced an executable proposal
The repaired proposal used the partitioned table:
SELECT category, ROUND(SUM(amount), 2) AS total_amountFROM "<S3_TABLES_CATALOG>"."lab"."events"WHERE event_date = DATE '2026-11-01'GROUP BY categoryORDER BY category;The accepted Bedrock interaction used 781 input tokens and 124 output tokens,
with 1,298 milliseconds of reported latency.
What mattered to me was not simply that the fourth attempt worked. It was that
the first three could not slip past the gate and reach execution.

Athena gave me a less convenient answer
Athena returned the same three aggregates for both layouts:
category | total_amount |
|---|---|
compute | 33,030.5 |
network | 33,200.0 |
storage | 33,269.5 |
The scan and timing measurements were:
layout | data scanned | engine time | total time |
|---|---|---|---|
Unpartitioned baseline | 3,652 bytes | 790 ms | 955 ms |
Partitioned candidate | 791 bytes | 934 ms | 1,087 ms |
The candidate scanned 2,861 fewer bytes—a 78.3% reduction. It also took 144
milliseconds longer in Athena engine time and 132 milliseconds longer end to
end.
On such a small fixture, startup and coordination overhead can dominate the
timing. It would have been easy to highlight the scan reduction, ignore the
slower run, and label the optimization a success. I did not think the evidence
earned that claim.
The conclusion I was comfortable making was much narrower:
The partitioned layout preserved the result and substantially reduced the measured Athena scan for this date-filtered query.
Before accepting the same change in production, I would want representative
data volume, concurrent workloads, controlled cache conditions, repeated
trials, and the organization's real cost model.

I asked two more engines for a second opinion
An Athena result alone was not enough for the experiment. I used cross-engine
agreement as another acceptance signal and read the same partitioned S3 Tables
data from:
- Amazon Athena
- Amazon EMR Serverless with Spark
- Amazon Redshift Serverless through an external schema
All three returned the same three values.
The successful EMR Serverless job reported 0.029 vCPU-hours, 0.087 memory
GB-hours, and 0.578 storage GB-hours. I kept those numbers as operational
evidence, but I did not turn one small run into a universal cost claim.
Glue Data Quality provided a separate check on the fixture. Its three rules
validated:
- exactly 10,000 rows
- complete
event_idvalues
-
categoryrestricted tocompute,storage, ornetwork
That run completed in 92 seconds with a score of 1.0.

The architecture diagram hides the messy parts
The final diagram makes the services look as though they clicked together on
the first try. They did not.
EMR Serverless needed a real network path
My first EMR attempt sat waiting on Maven dependency resolution. I replaced
that dependency path with a pinned S3 Tables Iceberg runtime JAR. The next
compatibility attempt failed, and a direct S3 Tables client attempt then timed
out because the job had no route for the outbound connection it needed.
For the successful run, I attached the application to a temporary private
subnet with controlled outbound access through a NAT gateway. After the Spark
result was captured, I removed the application, NAT gateway, Elastic IP,
subnets, route tables, and security group.
That was a useful reminder: “serverless” removes server management, not the
need to understand how a job reaches its dependencies and endpoints.
Redshift needed permission on the resource link
The Redshift external schema was created successfully, but the first queries
failed in Lake Formation even though the disposable role had permissions on
the target tables.
The missing permission was
DESCRIBE on the Glue resource-link database.
After adding it, Redshift returned the same three aggregates.The permission on the target was only half the story. When a query crosses a
Glue resource link, the link itself has to be included in the permission
check.
Glue Data Quality exposed two missing IAM actions
The first data-quality run failed because the execution role lacked permission
to read the evaluation run. The next attempt exposed a missing result-publish
permission.
I added only the required actions to the disposable role. The third run
succeeded.
This is why I wanted to build the lab instead of stopping at an architecture
diagram. The failures revealed the boundaries that are easy to miss on paper
and much harder to miss when a real job is failing.
What I would require before using this in production
This lab was intentionally small and disposable. A production implementation
would add:
- A representative replay set, not one generated query and one date.
- Multiple warm and cold trials, with medians and tail latency.
- Query timeout, scan, and concurrency budgets.
- A durable proposal ledger containing the prompt version, model version, policy version, SQL hash, measurements, and final decision.
- Human approval for changes to physical design or routing.
- A cost model that includes model invocation, validation queries, orchestration, storage, networking, and expected query frequency.
- Automatic expiration and cleanup controls for every validation resource.
I would also preserve the strict split between proposal generation and
execution credentials. The component calling Bedrock should not be able to run
arbitrary SQL. The executor should accept only a validated, content-addressed
proposal.
The lab was not finished until it was gone
Because this was a disposable lab, cleanup was part of the acceptance test,
not an item to handle later.
After preserving sanitized measurements and images, I removed the disposable
EMR and Redshift resources, Athena workgroup, Bedrock guardrail, Glue
resources, IAM role, S3 buckets, S3 Tables resources, NAT gateway, Elastic IP,
subnets, route tables, and security group.
A final read-only audit found no named service resources or tagged temporary
network resources left by the lab. I left the pre-existing VPC and internet
gateway unchanged.
The repository includes the cleanup-audit approach and excludes private logs,
generated state, account identifiers, and the downloaded runtime JAR.
What I am taking away from the experiment
Bedrock was genuinely useful. It found the intended optimization and repaired
an invalid proposal after receiving precise feedback. But the part I would
trust was not simply “AI writes SQL.”
It was this:
Bedrock proposes. Policy constrains. AWS engines measure. Deterministic evidence decides.
That is the boundary I would be comfortable building on: let the model
generate options, then make code and measured evidence decide what happens
next.
Try the lab yourself
If you want to try the workflow rather than just read about it, start with the
AI Lakehouse Query Lab on GitHub .
You can inspect the validator, reproduce the experiment, or adapt the
acceptance gate for your own analytics workload.
The repository includes:
- the deterministic Python proposal validator and unit tests
- the parameterized Bedrock tool-use request
- the EMR Serverless validation job
- the sanitized measurements and article visuals
- deployment, permission, and cleanup guidance
- a read-only cleanup audit script
Run the local test suite first:
python3 -m unittest discover -s tests -vBefore creating anything in AWS, read
DEPLOYMENT.md . Use a unique resource
prefix, select your AWS profile explicitly, and keep the resources disposable.
The repository does not include credentials, account identifiers, private
logs, or generated infrastructure state.References
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article