AWS Data Engineering
Amazon Athena: SQL on S3 Without Servers
DataForge AWS Data Engineering Series - Blog 12 of 20
The analytics team’s Athena workgroup had no query result limit and no per-query data scan cap. One analyst, testing a new dashboard, accidentally ran a SELECT * with no WHERE clause against a 40TB table — a table that existed specifically because it hadn't been cleaned up in over a year. The query itself failed after several minutes with a size limit error, but not before scanning enough data to generate a $200 charge for a single query that produced no usable output at all.
Nobody had set a per-query scan limit on the workgroup, because nobody had considered that a query could be run without a WHERE clause against a table that large. The fix was a five-minute configuration change — a workgroup-level data scan limit — that would have turned a $200 mistake into an immediately-rejected query with zero cost. The gap wasn’t technical difficulty. It was that Athena’s cost-control features are opt-in, and a team that hasn’t been burned yet usually hasn’t opted in.
Blog 7 introduced Athena as part of the compute decision framework. This article goes deep on making Athena actually safe and efficient to operate — the partitioning, format, and workgroup configuration that determine whether Athena is the cheapest service in your AWS data stack or the one with the least predictable bill.
Let’s go deep.
TL;DR
Athena is a serverless SQL query engine that reads directly from S3, billed per terabyte scanned. Its cost and performance are determined almost entirely by how the underlying data is organized — partitioning, file format, and file size — combined with workgroup-level guardrails that prevent a single mistaken query from generating an unexpectedly large bill. Understanding CTAS for materializing results, workgroups for cost isolation and control, and the Glue Data Catalog integration that ties it all together is what separates teams that use Athena safely from teams that get one unpleasant surprise on a monthly invoice.
By the end of this article you’ll be able to:
- Configure workgroups with data scan limits that make runaway queries impossible, not just unlikely
- Use CTAS and INSERT INTO to materialize query results, replacing entire classes of scheduled ETL jobs
- Apply partition projection to avoid the operational overhead of Glue crawlers for predictable partition schemes
- Diagnose and fix the specific query patterns that scan far more data than a query actually needs
Series context: This completes the Athena introduction from Blog 7 with full operational depth, and depends directly on Blog 2’s partitioning and Parquet principles — every technique in this article assumes those foundations are already in place.

The Cost Model, Precisely
Athena’s pricing is simple to state and easy to misjudge in practice: $5 per terabyte of data scanned, with a minimum charge per query (typically 10MB minimum scan).
The cost equation:
Cost = (data scanned in TB) x $5
What "data scanned" actually means:
NOT the size of the query result
NOT the size of the entire table
The size of the data Athena had to READ from S3
to compute the result - which depends entirely on
partition pruning and columnar format effectiveness
(Blog 2's principles, applied directly)
Example - same logical query, wildly different cost:
Unpartitioned CSV, 8TB table, filtering one day:
scans all 8TB -> $40
Partitioned Parquet, same 8TB table, same filter:
scans ~30GB (one partition, columnar) -> $0.15
This is Blog 2’s mechanism walkthrough restated in Athena’s specific billing terms — the same underlying principle, now expressed as a direct line item on an AWS invoice.
Workgroups: The Control Plane Most Teams Never Configure
A workgroup is Athena’s mechanism for isolating and controlling query execution - cost limits, IAM permissions, and query result locations are all scoped per workgroup.
What a workgroup controls:
Per-query data scan limit
Reject any single query that would scan more
than a specified amount of data, BEFORE it runs
to completion and generates a full charge
Per-workgroup data scan limit (with SNS alerting)
Track cumulative scan volume across all queries
in the workgroup within a period, alerting or
blocking once a threshold is reached
Query result location
Where CSV/JSON result files land in S3 -
important because these accumulate and cost
money if not lifecycle-managed (Blog 2's
lifecycle policy principles apply directly)
IAM permissions scoping
Different workgroups can have different
permission boundaries - separating, for example,
an "ad hoc analyst" workgroup from an "automated
ETL" workgroup with different access levels
The specific configuration that would have prevented the opening scenario:
{
"WorkGroupConfiguration": {
"BytesScannedCutoffPerQuery": 10737418240,
"EnforceWorkGroupConfiguration": true,
"PublishCloudWatchMetricsEnabled": true
}
}BytesScannedCutoffPerQuery set to 10GB (in this example) means any query estimated to scan more than that limit is rejected before execution — not after it completes and the charge is already incurred. This is the single highest-leverage cost control in Athena, and it's off by default.
Why teams skip this: setting a scan limit too low breaks legitimate large queries, and figuring out the right threshold requires knowing your actual query patterns — which teams often don’t examine until after a cost incident, rather than before one.
CTAS: Materializing Query Results, Replacing Scheduled Jobs
CREATE TABLE AS SELECT (CTAS) runs a query and writes its results as a new table — the mechanism referenced in Blog 7 that can replace entire categories of Glue jobs for SQL-expressible transformations.
CREATE TABLE gold.daily_revenue_summary
WITH (
format = 'PARQUET',
external_location = 's3://bucket/gold/daily_revenue/',
partitioned_by = ARRAY['event_date']
) AS
SELECT
event_date,
region,
product_category,
SUM(revenue) AS total_revenue,
COUNT(DISTINCT customer_id) AS unique_customers
FROM silver.events
WHERE event_date >= DATE '2024-01-01'
GROUP BY event_date, region, product_category;What CTAS gives you beyond a plain SELECT:
The query result is materialized as an actual table,
registered in the Glue Data Catalog automatically
Output format, compression, and partitioning are
all explicitly controllable - you can convert row-based
source data to Parquet AS PART OF the query itself
Downstream queries against the materialized table
are cheap (they scan the small aggregated result,
not the original large source)INSERT INTO for incremental materialization:
INSERT INTO gold.daily_revenue_summary
SELECT
event_date, region, product_category,
SUM(revenue), COUNT(DISTINCT customer_id)
FROM silver.events
WHERE event_date = CURRENT_DATE - INTERVAL '1' DAY
GROUP BY event_date, region, product_category;This is the pattern behind Blog 7’s cost comparison — a scheduled Athena query using INSERT INTO to append one new day's aggregated data, replacing what would otherwise be a daily Glue job, at a small fraction of the cost when the source data is properly partitioned.
Partitioning in Athena: How the Catalog Actually Prunes
This is the mechanism worth understanding precisely, because it explains exactly why a missing partition registration silently defeats the partitioning strategy from Blog 2.
Two ways Athena knows about partitions:
1. Glue Crawler (Blog 5) or MSCK REPAIR TABLE
Scans S3 and registers each partition directory
as a distinct entry in the Glue Data Catalog with
its own S3 location
2. Explicit ALTER TABLE ADD PARTITION
Manually (or via pipeline code) register each new
partition immediately when it's written, without
waiting for a crawler run
What happens if a partition ISN'T registered in the
Catalog, even though the data exists in S3 in the
correctly partitioned structure:
Athena's query planner only knows about partitions
present in the Catalog. Data sitting in
s3://bucket/events/year=2024/month=06/day=15/
that was never registered (crawler hasn't run yet,
or ALTER TABLE ADD PARTITION was never called) is
INVISIBLE to Athena - queries silently return
incomplete results for that date range, with no
error indicating data exists but isn't being read
Why this is dangerous, not just inconvenient: unlike a query that fails loudly, a query against unregistered partition data returns a result — it’s just an incomplete one, and nothing distinguishes “there’s no data for this date” from “there’s data but the Catalog doesn’t know about it.” This is the Athena-specific version of the silent correctness failures covered throughout the Databricks series.
Partition Projection: Eliminating the Crawler Dependency
For partition schemes that follow a predictable pattern (sequential dates, a known enumerated list of regions), partition projection lets Athena calculate partition locations mathematically instead of looking them up in the Glue Catalog at all.
CREATE EXTERNAL TABLE silver.events (
event_id STRING,
revenue DECIMAL(18,2)
)
PARTITIONED BY (event_date STRING)
STORED AS PARQUET
LOCATION 's3://bucket/silver/events/'
TBLPROPERTIES (
'projection.enabled' = 'true',
'projection.event_date.type' = 'date',
'projection.event_date.range' = '2023-01-01,NOW',
'projection.event_date.format' = 'yyyy-MM-dd',
'storage.location.template' = 's3://bucket/silver/events/event_date=${event_date}/'
);What this eliminates: no crawler needs to run, ever, to discover new date partitions — Athena calculates that 2024-06-15 maps to s3://bucket/silver/events/event_date=2024-06-15/ directly from the projection rule, without any Catalog lookup or crawler dependency. This solves both the crawler cost problem from Blog 5 and the partition registration gap described above, for any partition scheme that's genuinely predictable (sequential dates, a known fixed list of regions or categories).
When partition projection doesn’t fit: partition values that aren’t predictable from a formula — arbitrary customer IDs, dynamically discovered categories — still need actual Catalog-based partition discovery via crawlers or explicit registration.
Federated Query: Reaching Beyond S3
Athena Federated Query lets a single query join data across S3 and other data sources — RDS, DynamoDB, even on-premises databases — via Lambda-based data source connectors.
SELECT
s.event_id, s.revenue,
r.customer_name
FROM s3_events.silver_events s
JOIN rds_connector.public.customers r
ON s.customer_id = r.customer_id
WHERE s.event_date = DATE '2024-01-15';How this actually executes: the Lambda-based connector for the non-S3 source (RDS in this example) is invoked to fetch the relevant rows from the external system, which Athena’s query engine then joins with the S3-based data. This adds Lambda’s constraints (Blog 10) into the query path — a federated query against a very large external table can hit Lambda’s timeout or memory limits in ways a pure S3 query never would.
When federated query is the right tool: occasional cross-source analytical queries where standing up a full ETL pipeline to copy the external data into S3 isn’t justified by the query frequency. When it isn’t: frequent, performance-critical queries joining large external datasets — at that point, replicating the external data into S3 (via DMS, a Glue JDBC connector, or Lakeflow Connect-equivalent CDC patterns) and querying it natively is more efficient and doesn’t carry Lambda’s constraints into every query execution.
Common Query Patterns That Scan More Than They Need To
Beyond the structural partitioning and format decisions from Blog 2, specific SQL patterns within Athena queries can silently defeat optimizations that are otherwise correctly configured.
-- Pattern 1: function wrapping a partition column defeats pruning
-- BAD — Athena can't prune partitions when the column is wrapped
SELECT * FROM events
WHERE DATE(event_timestamp) = DATE '2024-01-15';
-- GOOD — filter directly on the partition column
SELECT * FROM events
WHERE event_date = '2024-01-15';
-- Pattern 2: SELECT * when only specific columns are needed
-- BAD — reads every column's data blocks even in Parquet
SELECT * FROM events WHERE event_date = '2024-01-15';
-- GOOD — only reads the columns actually referenced
SELECT event_id, revenue FROM events
WHERE event_date = '2024-01-15';
-- Pattern 3: implicit type casting preventing predicate pushdown
-- BAD — comparing a string partition column to an integer literal
-- can force a cast that defeats pruning in some engine versions
SELECT * FROM events WHERE event_year = 2024;
-- GOOD — match the partition column's actual stored type
SELECT * FROM events WHERE event_year = '2024';The general principle underlying all three patterns: Athena’s query planner can only prune partitions and skip columns when the query’s filter and select clauses map directly and unambiguously onto the underlying partition and column structure. Any transformation applied to a partition column in the WHERE clause, or any unnecessary column selected, works against the exact optimizations Blog 2’s file layout was designed to enable.
Architecture Flow: Athena’s Place in the Serving Layer
S3 Silver/Gold Layer (Blog 2's partitioning + Parquet)
|
+-- Registered via Glue Crawler, explicit
| ALTER TABLE ADD PARTITION, or partition
| projection (no Catalog dependency)
|
v
+-------------------------------------------------+
| Glue Data Catalog |
| (shared metadata layer - also used by |
| Redshift Spectrum, Blog 6) |
+----------------------+--------------------------+
|
v
+-------------------------------------------------+
| Athena |
| |
| Workgroup: ad-hoc-analysts |
| Scan limit: 10GB/query |
| Result location: s3://.../athena-results/ |
| |
| Workgroup: scheduled-etl |
| Different IAM scope, higher scan limit |
| Runs CTAS/INSERT INTO on a schedule |
| (EventBridge-triggered, Blog 11-style |
| orchestration) |
+-------------------------------------------------+
|
+-----------+-----------+
v v
Ad hoc analysis Materialized Gold
(BI tools, direct tables (fast, cheap
SQL queries) downstream reads)Failure Modes You’ll See in Production
No workgroup scan limit configured, one query causes an unexpected charge. The opening scenario. A missing WHERE clause against a large, unpartitioned or poorly partitioned table scans far more data than intended, and without a BytesScannedCutoffPerQuery limit, the query runs to completion and the full cost is incurred before anyone notices.
Unregistered partitions causing silently incomplete query results. New data lands in S3 in the correct partition structure, but the crawler hasn’t run yet (or explicit partition registration was never implemented in the pipeline). Queries against that date range return zero or partial rows, and because the query succeeds without error, the gap looks like “there’s no data for that period” rather than “the data exists but Athena doesn’t know about it yet.”
A function wrapping the partition column silently disabling pruning. A query written with WHERE DATE(event_timestamp) = ... instead of filtering the partition column directly scans the entire table every time, at full cost, while every other aspect of the table's design (correct partitioning, Parquet format) is configured properly — the cost problem originates entirely in query-writing habits, not infrastructure.
Federated Query against a large external table hitting Lambda’s limits. A federated query joining S3 data to a large RDS table times out or fails because the underlying Lambda connector hits Blog 10’s 15-minute ceiling or memory limits while fetching the external rows — a failure mode that looks like an Athena problem but is actually Lambda’s constraints surfacing through the federated connector.
Query result files accumulating in S3 with no lifecycle policy. Every Athena query (outside of CTAS materialization) writes a result file to the workgroup’s configured S3 location. Without a lifecycle policy (Blog 2) on that location, months of ad hoc query results accumulate indefinitely, incurring ongoing storage costs for output nobody will ever look at again.
Partition projection misconfigured with an incorrect date range or format. A partition projection rule’s date range is set with a fixed end date instead of NOW, and six months later, queries for recent dates silently return no results because the projection formula no longer generates locations for dates beyond the hardcoded range — a configuration that was correct at setup time and silently stopped being correct as time passed.
Trade-offs: What Athena Optimizes For
Athena optimizes for:
- Zero infrastructure for SQL analytics — no cluster, no warehouse to manage
- True pay-per-query economics with no idle cost
- Direct querying of data already in S3, without a separate load step
- Fast time-to-first-query for ad hoc analysis on data that’s already well-organized
Athena doesn’t optimize for:
- Cost predictability without deliberate workgroup configuration — the default posture has no scan limits
- High-concurrency, complex-join workloads at the scale Redshift (Blog 6) is built for
- Query performance on poorly organized data — Athena inherits every consequence of Blog 2’s file layout decisions directly and immediately
- Sub-second latency — even well-optimized Athena queries have meaningful startup overhead compared to a warmed Redshift cluster
The honest trade-off: Athena’s zero-infrastructure model means its safety and cost-efficiency are entirely a function of configuration choices you make deliberately — workgroup limits, partition strategy, query patterns — rather than anything the service enforces by default. This is the same “convenience trades for required configuration diligence” pattern seen throughout this series, expressed here as the gap between Athena’s default posture and its safely-operated posture.
Real-World Constraints
Query timeout and concurrency limits. Athena queries have a maximum execution time (30 minutes by default, adjustable) and workgroups have concurrent query execution limits. High-concurrency ad hoc analytical workloads can hit these limits during peak usage, requiring either workgroup-level tuning or acknowledging that Redshift (Blog 6) may be the better fit for that specific concurrency profile.
DDL limitations compared to a full data warehouse. Athena’s DDL (via Presto/Trino’s engine) doesn’t support every operation a traditional warehouse does — certain complex ALTER TABLE operations, some constraint types, and specific SQL dialect features differ from Redshift or traditional RDBMS syntax, worth validating early in a migration rather than assuming full portability.
Cross-region query costs. Querying data in an S3 bucket in a different region than the Athena workgroup incurs cross-region data transfer charges in addition to the standard per-TB-scanned cost — a cost dimension easy to miss when Athena’s simple pricing model (just $5/TB) is assumed to be the complete picture.
What This Means for the Rest of the Series
Blog 13 (Medallion on AWS): Athena is frequently the
Silver-to-Gold materialization
engine (via CTAS) in a complete
Medallion implementation
Blog 18 (Cost optimization): workgroup scan limits and
the query pattern fixes from
this article are core items
in the broader AWS cost audit
checklist
Summary: The Engineering Lesson
Athena’s simplicity is real — there’s genuinely no cluster to manage and no warehouse to provision. But that simplicity creates a specific risk: a service with no default cost guardrails, where the entire safety model depends on configuration choices (workgroup limits, correct partitioning, disciplined query patterns) that are easy to skip when nothing has gone wrong yet.
The $200 query from the opening scenario wasn’t a flaw in Athena. It was the predictable consequence of a workgroup running with every safety feature available and none of them turned on — the equivalent of driving a car with a functioning seatbelt that nobody buckled.
Athena’s cost model rewards exactly the same discipline this entire series has argued for: partition deliberately, format correctly, and configure the guardrails before you need them, not after the invoice arrives.
Next in Series
Blog 13 - Building a Medallion Architecture on AWS
Phase 2 is complete — every core compute, storage, and orchestration service has been covered individually. Blog 13 begins Phase 3 by assembling them: a complete Bronze/Silver/Gold implementation on AWS, showing exactly which service handles each layer and why, building on every article from this phase.
We’ll go deep on the AWS-specific equivalent of Unity Catalog (Glue Data Catalog + Lake Formation), and how the ingestion, transformation, and serving patterns from Blogs 4 through 12 compose into one coherent architecture.
Comment Below
What’s the most expensive Athena query mistake you’ve seen — yours or someone else’s?
Was it a missing WHERE clause against an unpartitioned table with no workgroup scan limit to catch it before the full cost was incurred? A function wrapping a partition column that silently disabled pruning for months while every other part of the pipeline looked correctly configured? Data that existed in S3 but returned zero rows because a partition was never registered in the Catalog?
And - was the fix a query rewrite, or a workgroup configuration nobody had thought to set up?
Tags: aws-data-engineering, amazon-athena, ctas, partition-projection, workgroups, glue-data-catalog, federated-query, cost-optimization, dataforge