# Amazon Athena: A Practical Guide to SQL on Files in S3

Three months of load balancer logs are sitting in an S3 bucket: thousands of compressed files, a few hundred gigabytes. Something odd happened last Tuesday and you need to know which addresses hit the login page most that afternoon.

You could download the files and write a script. You could start a database, design a table and load everything first. Or you could describe the files once, write one SQL query and have the answer in under a minute, with nothing to start beforehand and nothing to shut down afterwards.

The third option is Amazon Athena. It is the odd one out among the cloud warehouses, because it is not really a warehouse at all. There is no database to load. Your files are the database, and how you lay them out is your schema design.

## What Athena is

Athena is a serverless query service from AWS. It runs SQL directly against files in Amazon S3. Its SQL engine is built on the open-source Trino project (and on Presto in older engine versions), so the dialect is standard and rich.

Three pieces work together:

| Piece | Role |
|---|---|
| Amazon S3 | Holds the data files: CSV, JSON, Parquet, ORC and others |
| AWS Glue Data Catalog | Holds the table definitions: column names, types, file format and the S3 location |
| Athena | Reads the catalog, scans the files and returns the result |

A table in Athena is only a description. `CREATE TABLE` writes a few lines of metadata. `DROP TABLE` on an ordinary external table removes that description and leaves the files untouched.

Every query also writes its result as a file to an S3 location you choose. That is why Athena always asks for a "query result location".

## Why teams choose it

- **Nothing to run.** No cluster, no warehouse, no idle cost. If nobody queries, Athena costs nothing.
- **No loading step.** Data that lands in S3 is queryable as soon as a table describes it.
- **Open formats.** The files stay in your bucket in formats that Spark, Redshift Spectrum, DuckDB and many other tools can read too.
- **A good fit for AWS logs.** CloudTrail, load balancer, VPC flow and CloudFront logs all arrive in S3, and AWS documents a table definition for each.
- **Fine-grained access through IAM.** The same policies that guard the bucket guard the queries.

## Where Athena fits, and where it does not

**A strong choice for:**

- Ad hoc questions over logs and event files
- Occasional reporting on a data lake
- Investigations, audits and one-off analysis
- A cheap first analytics stack when data is already in S3

**Look elsewhere when:**

- **Dashboards must answer in well under a second.** Every Athena query has a start-up delay and reads from S3. Use a warehouse or an engine such as ClickHouse.
- **Many users query all day.** Paying per query adds up, and there are limits on how many queries run at once. A provisioned Redshift cluster or a Snowflake warehouse is easier to budget.
- **Rows change often.** Plain files are written once. Athena can update and delete rows in Apache Iceberg tables, but it is not a transactional database.
- **Your data is not in AWS.** BigQuery on Google Cloud offers a similar pay-per-query model with managed storage.
- **You want the database to manage storage for you.** In Athena, file sizes, formats and folder layout are your responsibility.

## How the pricing shapes your habits

By default Athena charges for the amount of data each query scans. Not for time, not for rows returned. A few consequences:

- Statements that only change metadata, such as `CREATE TABLE` or `ALTER TABLE ADD PARTITION`, are not charged. Failed queries are not charged either. A query you cancel is charged for what it had scanned so far.
- Compressed files count at their compressed size, so compression directly reduces the bill.
- A columnar format lets Athena read only the columns you name.
- Partitions let Athena skip whole folders.

You also pay the normal S3 charges for storing the data and the results, and for the requests Athena makes. For steady heavy use there is a capacity option where you reserve compute instead of paying per query.

So the rule is simple: **the less data a query must read, the less it costs and the faster it runs.** Everything below serves that rule.

## Using it the right way

### Describe your files

Suppose JSON logs arrive under `s3://my-data-bucket/raw/access_logs/`:

```sql
CREATE EXTERNAL TABLE access_logs_raw (
  request_time string,
  client_ip    string,
  path         string,
  status       int,
  bytes_sent   bigint
)
ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
LOCATION 's3://my-data-bucket/raw/access_logs/';
```

`LOCATION` is a folder, never a single file. Athena reads every file under it.

This works, and it is the expensive way to query: each query reads every byte of every file.

### Convert to Parquet and partition by date

A `CREATE TABLE AS` statement (CTAS) rewrites the data in a better shape:

```sql
CREATE TABLE access_logs
WITH (
  format = 'PARQUET',
  write_compression = 'SNAPPY',
  external_location = 's3://my-data-bucket/curated/access_logs/',
  partitioned_by = ARRAY['day']
) AS
SELECT client_ip, path, status, bytes_sent,
       CAST(from_iso8601_timestamp(request_time) AS timestamp) AS request_time,
       substr(request_time, 1, 10) AS day
FROM access_logs_raw;
```

Partition columns must come last in the `SELECT`. The result is one folder per day, such as `day=2026-03-03/`, full of Parquet files. A single CTAS statement can write a limited number of partitions (100), so convert a long history in several runs with `INSERT INTO`.

Now the opening question is cheap:

```sql
SELECT client_ip, count(*) AS hits
FROM access_logs
WHERE day = '2026-03-03'
  AND path = '/login'
GROUP BY client_ip
ORDER BY hits DESC
LIMIT 20;
```

Athena opens one day's folder and reads two columns.

### Keep partitions registered

When new day folders arrive from another tool, the catalog has to learn about them. There are three ways:

```sql
-- Scan the location for Hive-style folders (day=...)
MSCK REPAIR TABLE access_logs;

-- Or add one explicitly, which is faster on big tables
ALTER TABLE access_logs ADD IF NOT EXISTS
  PARTITION (day = '2026-03-04')
  LOCATION 's3://my-data-bucket/curated/access_logs/day=2026-03-04/';
```

The third way is **partition projection**: you tell Athena the pattern and it works out the partitions itself, with nothing to register.

```sql
ALTER TABLE access_logs SET TBLPROPERTIES (
  'projection.enabled' = 'true',
  'projection.day.type' = 'date',
  'projection.day.format' = 'yyyy-MM-dd',
  'projection.day.range' = '2024-01-01,NOW',
  'storage.location.template' = 's3://my-data-bucket/curated/access_logs/day=${day}/'
);
```

For date-based data that arrives every day, projection is usually the least work.

### Put guard rails on a workgroup

A workgroup is a named set of query settings. It can fix the result location and refuse any query that scans too much:

```bash
aws athena create-work-group --name analysts \
  --configuration "ResultConfiguration={OutputLocation=s3://my-athena-results/analysts/},EnforceWorkGroupConfiguration=true,BytesScannedCutoffPerQuery=10737418240"
```

With that setting, a query in the `analysts` workgroup is cancelled once it has scanned 10 GB. Give each team its own workgroup and you can also see spending per team.

Add an S3 lifecycle rule on the results bucket so old result files expire. Otherwise they pile up forever.

### Use Iceberg when rows must change

```sql
CREATE TABLE orders (
  order_id   bigint,
  status     string,
  created_at timestamp
)
PARTITIONED BY (day(created_at))
LOCATION 's3://my-data-bucket/iceberg/orders/'
TBLPROPERTIES ('table_type' = 'ICEBERG');

UPDATE orders SET status = 'refunded' WHERE order_id = 1001;
```

Apache Iceberg is an open table format that tracks files in its own metadata, which makes `UPDATE`, `DELETE` and `MERGE INTO` possible. Run `OPTIMIZE orders REWRITE DATA USING BIN_PACK;` now and then to merge the small files those changes leave behind.

### Mind the two quoting styles

Queries follow Trino rules: single quotes for strings, double quotes for identifiers. DDL statements follow Hive rules, where identifiers take backticks. A column called `order` is `"order"` in a `SELECT` and `` `order` `` in a `CREATE TABLE`.

## Common mistakes

- **Querying raw CSV or JSON forever.** Converting to Parquet is usually the biggest single saving.
- **No partition filter.** A query without one scans every partition.
- **Too many tiny files.** Thousands of kilobyte-sized files are slow to list and open. Aim for fewer, larger files.
- **Too many partitions.** Partitioning by hour and by customer can produce millions of folders with a few rows each. Partition on what you filter by, at a sensible grain.
- **`SELECT *` on a wide table.** It reads every column and defeats the columnar format.
- **Forgetting new partitions.** The data is in S3 but queries return nothing for that day. Register it, or use projection.
- **A results bucket that never expires.** It holds copies of your query results, including sensitive ones.
- **Broad IAM permissions.** An identity that queries needs Athena and Glue read actions, read access to the data bucket and write access to the results location. It does not need all of S3.

## Quick reference

| Task | Command |
|---|---|
| List databases | `SHOW DATABASES;` |
| List tables | `SHOW TABLES IN weblogs;` |
| Show a table's definition | `SHOW CREATE TABLE access_logs;` |
| List partitions | `SHOW PARTITIONS access_logs;` |
| Find new partitions | `MSCK REPAIR TABLE access_logs;` |
| Which file a row came from | `SELECT "$path" FROM access_logs LIMIT 5;` |
| See the plan | `EXPLAIN SELECT ...;` |
| Run from the CLI | `aws athena start-query-execution --query-string "SELECT 1" --work-group analysts` |
| Check a query's cost driver | `aws athena get-query-execution --query-execution-id <id>` (see `DataScannedInBytes`) |

With Athena you do the storage engineering yourself: columnar files, date partitions, sensible file sizes and a workgroup limit. Do that once and it stays one of the cheapest ways to ask a big question.

## Exploring Athena with CreamDB

The Athena console works well for one account. When you want Athena beside your other databases, [CreamDB](https://www.creamdb.com) connects to it from a browser tab with nothing to install.

- Connect with a region, an access key and secret key, a workgroup, an S3 result location and a default database. CreamDB uses only the keys you give it, and the secret key is stored encrypted. Create an IAM user for this with the narrow permissions described above.
- Browse the databases, tables and columns from the Glue Data Catalog in a tree.
- Write SQL in an editor with autocomplete, formatting and history, and export results to CSV, JSON or Excel.
- Ask in plain English, for example "requests per day by status code last week", and get the SQL, a result table and a chart.

The assistant only reads on its own. Any change waits as an approval card that you answer.

One practical point: each question the assistant asks is a real Athena query that scans data. Connect through a workgroup with a scan limit, and keep your tables partitioned. It is free to start.

