HW3 - Querying Data with Athena (Detailed Guide)
DES431 — HW3: Querying Data by Using Athena
Complete Detailed Guide — All 7 Tasks (AWS Academy Data Engineering, Module 4)
Duration: ~90 minutes Scenario: You're on the data science team. A colleague, Mary, needs to run advanced SQL on taxi trip CSV data spread across multiple files in S3. You'll build a proof of concept using AWS Glue + Athena, then package a reusable query for her team using CloudFormation, and confirm her access works via IAM.
Part 0 — Starting the Lab
- At the top of the lab instructions, click ▶ Start Lab.
- Wait until the circle icon next to the AWS link (top-left) turns green.
- Click the AWS link — a new tab opens to the AWS Management Console.
- If a pop-up blocker prevents the tab from opening, allow pop-ups for the site and retry.
💡 If your session is about to time out, click Start Lab again before the timer hits
00:00to refresh it.
Task 1 — Creating and Querying an AWS Glue Database and Table in Athena
Goal: Define a schema for a table so you can run SQL against the raw CSV data.
Step 1.1 — Open Athena
In the AWS Console search bar, search for and open Athena.
Step 1.2 — Set the Query Result Location
Athena requires an S3 bucket to store query results before you can run anything.
- Choose Explore the query editor.
- Go to the Settings tab.
- Under Query result and encryption settings, click Manage.
- For Location of query result, click Browse S3 and select the bucket that was pre-created for you.
- Click Choose, keep other defaults, then Save. (You don't need to set an "Expected bucket owner".)
Step 1.3 — Create the Glue Database
-
Go to the Editor tab.
-
In the Query 1 box, run:
CREATE DATABASE taxidata; -
You should see Query successful — this creates a Glue database named
taxidata.
🔎 To confirm: open the AWS Glue console → Databases in a new tab.
taxidatashould be listed.
Step 1.4 — Create a Table and Import Data
-
In Athena, under Tables and views, click Create → S3 bucket data.
-
Fill in:
-
Table name:
yellow -
Description:
Table for taxi data -
Database configuration: Choose an existing database →
taxidata -
Location of input dataset:
s3://aws-tc-largeobjects/CUR-TF-200-ACDSCI-1/Lab2/yellow/ -
Encryption: leave unselected (default)
-
Data format:
CSV
-
-
In Column details, click Bulk add columns, paste:
vendor string,pickup timestamp,dropoff timestamp,count int,distance int,ratecode string,storeflag string,pulocid string,dolocid string,paytype string,fare decimal,extra decimal,mta_tax decimal,tip decimal,tolls decimal,surcharge decimal,total decimalthen click Add.
-
Review the generated Preview table query — it should match:
CREATE EXTERNAL TABLE IF NOT EXISTS taxidata.yellow ( `vendor` string, `pickup` timestamp, `dropoff` timestamp, `count` int, `distance` int, `ratecode` string, `storeflag` string, `pulocid` string, `dolocid` string, `paytype` string, `fare` decimal, `extra` decimal, `mta_tax` decimal, `tip` decimal, `tolls` decimal, `surcharge` decimal, `total` decimal ) ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' WITH SERDEPROPERTIES ( 'serialization.format' = ',', 'field.delim' = ',' ) LOCATION 's3://aws-tc-largeobjects/CUR-TF-200-ACDSCI-1/Lab2/yellow/' TBLPROPERTIES ('has_encrypted_data'='false');(SerDe = "Serializer/Deserializer" — it tells Athena how to parse each row; here, comma-delimited.)
-
Click Create table → Query successful.
Step 1.5 — Preview the Data
- Under Data, for Database, select
taxidata. - Next to the
yellowtable, click the ⋮ (ellipsis) → Preview Table. - The first 10 records display in Results.
- Close open query tabs (X on each tab → Close query) — Athena allows a max of 10 active query tabs.
✅ Task 1 summary: You created a Glue database + table (taxidata.yellow), pointed it at raw CSV in S3, and defined the schema manually via bulk add columns (instead of using a Glue Crawler).
Task 2 — Optimizing Athena Queries by Using Buckets (Bucketizing)
Goal: Reduce cost/time by isolating high-cardinality data into its own file/table.
Cardinality refresher: High cardinality = a field with mostly unique values (e.g., exact timestamps). Low cardinality = a field with few distinct values (e.g.,
paytype: only 6 possible values). Bucketizing suits high-cardinality data; partitioning suits low-cardinality data (Task 3).
Step 2.1 — Create the jan Table
In a new query tab, run:
CREATE EXTERNAL TABLE IF NOT EXISTS jan (
`vendor` string,
`pickup` timestamp,
`dropoff` timestamp,
`count` int,
`distance` int,
`ratecode` string,
`storeflag` string,
`pulocid` string,
`dolocid` string,
`paytype` string,
`fare` decimal,
`extra` decimal,
`mta_tax` decimal,
`tip` decimal,
`tolls` decimal,
`surcharge` decimal,
`total` decimal
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
WITH SERDEPROPERTIES (
'serialization.format' = ',',
'field.delim' = ','
) LOCATION 's3://aws-tc-largeobjects/CUR-TF-200-ACDSCI-1/Lab2/January2017/'
TBLPROPERTIES ('has_encrypted_data'='false');This points to a separate S3 file that already contains only January 2017 data (pre-split from the full-year file).
Step 2.2 — Baseline: Query the Full-Year Table for January
SELECT count (count) AS "Number of trips" ,
sum (total) AS "Total fares" ,
pickup AS "Trip date"
FROM yellow WHERE pickup
between TIMESTAMP '2017-01-01 00:00:00'
and TIMESTAMP '2017-02-01 00:00:01'
GROUP BY pickup;Note the run time and data scanned shown after the query completes.

Step 2.3 — Compare: Query the Bucketized jan Table
SELECT count (count) AS "Number of trips" ,
sum (total) AS "Total fares" ,
pickup AS "Trip date"
FROM jan
GROUP BY pickup;You should see significantly less data scanned — because this table's underlying file only contains January data, Athena never has to touch the other 11 months.
✅ Task 2 summary: Isolating a high-cardinality subset (all of January, by exact timestamp) into its own S3 file/table cuts scan cost/time vs. scanning the whole year and filtering.

Task 3 — Optimizing Athena Queries by Using Partitions
Goal: Use a low-cardinality field (paytype, only 6 possible values) to partition data and store it in a compressed columnar format.
paytype codes:
| Code | Meaning |
|---|---|
| 1 | Credit card |
| 2 | Cash |
| 3 | No charge |
| 4 | Dispute |
| 5 | Unknown |
| 6 | Voided trip |
Step 3.1 — Create a Partitioned, Columnar Table
CREATE TABLE taxidata.creditcard
WITH (
format = 'PARQUET'
)AS
SELECT * from "yellow"
WHERE paytype = '1';This uses CTAS (CREATE TABLE AS SELECT) to build a new table, converting the result into Parquet (columnar) format — only credit-card (paytype = '1') rows.
Expected approx. result:
Time in queue: 251 ms
Run time: 28.572 sec
Data scanned: 9.32 GB
(This step reads the whole yellow table once to build the new table — hence the larger scan here.)

Step 3.2 — Query the Non-Partitioned Table
SELECT sum (total), paytype FROM yellow
WHERE paytype = '1' GROUP BY paytype;Expected approx. result:
Time in queue: 215 ms
Run time: 8.081 sec
Data scanned: 9.32 GB

Step 3.3 — Query the Partitioned/Parquet Table
SELECT sum (total), paytype FROM creditcard
WHERE paytype = '1' GROUP BY paytype;Expected approx. result:
Time in queue: 204 ms
Run time: 2.259 sec
Data scanned: 73.22 MB
Compare: 9.32 GB scanned vs. 73.22 MB scanned — ~99% less data scanned, and run time drops from ~8s to ~2.3s, for the same result. This is the direct, billable benefit of partitioning + columnar storage.
✅ Task 3 summary: Partitioning on a low-cardinality field, combined with switching to Parquet, drastically reduces both cost and latency.
Task 4 — Using Athena Views
Goal: Hide query complexity behind reusable views; combine multiple tables/views with a join.
Athena runs one SQL statement at a time — views let you effectively "save" a query and build on top of it.
Step 4.1 — Create a View for Credit Card Totals
CREATE VIEW cctrips AS
SELECT "sum"("fare") "CreditCardFares"
FROM yellow
WHERE ("paytype"='1');Step 4.2 — Create a View for Cash Totals
CREATE VIEW cashtrips AS
SELECT "sum"("fare") "CashFares"
FROM yellow
WHERE ("paytype"='2');Both views now appear under Views in the left panel.
Step 4.3 — Query Each View
Select * from cctrips;
Select * from cashtrips;
(Note these each scan ~9.32 GB — views don't inherently reduce scan cost; they're just saved query logic, not physically optimized storage like Task 3's Parquet table.)
Step 4.4 — Create a View That Joins Two Sub-Queries, Grouped by Vendor
CREATE VIEW comparepay AS
WITH
cc AS
(SELECT sum(fare) AS cctotal,
vendor
FROM yellow
WHERE paytype = '1'
GROUP BY paytype, vendor),
cs AS
(SELECT sum(fare) AS cashtotal,
vendor, paytype
FROM yellow
WHERE paytype = '2'
GROUP BY paytype, vendor)
SELECT cc.cctotal, cs.cashtotal
FROM cc
JOIN cs
ON cc.vendor = cs.vendor;This uses a CTE (WITH ... AS) to compute per-vendor credit-card and cash totals separately, then joins them together.
Step 4.5 — Preview the Joined View
- Under Views, next to
comparepay, click ⋮ → Preview View. - If prompted, choose Open query.
Expected result (approx.):
# cctotal cashtotal
1 584502884 250849783
2 460097126 199181978

✅ Task 4 summary: You built simple views, then a view combining two CTEs with a JOIN — this is how you package multi-table analysis for less-technical downstream users (like Mary's colleagues) without exposing the underlying SQL.
Task 5 — Creating Athena Named Queries by Using CloudFormation
Goal: Package a query as reusable infrastructure-as-code so other AWS accounts/departments can deploy it without writing SQL themselves.
Step 5.1 — Run Mary's Example Query First
SELECT distance, paytype, fare, tip, tolls, surcharge, total
FROM yellow
WHERE total >= 100.0
ORDER BY total DESCThis returns high-value trips (≥ $100 total), most expensive first. Run it in the Athena editor to confirm it works before templating it.

Step 5.2 — Open the IDE
- Copy the
LabIDEURLvalue (from the panel on the left of the lab instructions) into a new browser tab.https://d267bhico2drzj.cloudfront.net/?folder=/home/ec2-user/environment
- When prompted, enter the
LabIDEPasswordvalue.
Step 5.3 — Create the CloudFormation Template
-
In the IDE: File → New File.
-
Save it as
athenaquery.cf.yml(keep it open). -
Paste in:
AWSTemplateFormatVersion: 2010-09-09Resources: AthenaNamedQuery: Type: AWS::Athena::NamedQuery Properties: Database: "taxidata" Description: "A query that selects all fares over $100.00 (US)" Name: "FaresOver100DollarsUS" QueryString: > SELECT distance, paytype, fare, tip, tolls, surcharge, total FROM yellow WHERE total >= 100.0 ORDER BY total DESCOutputs: AthenaNamedQuery: Value: !Ref AthenaNamedQuerySave the file.
⚠️ YAML is whitespace-sensitive. If validation fails with "YAML not well-formed," check indentation and spacing carefully — don't mix tabs and spaces.
What this template does:
- Creates an Athena named query resource.
- Assumes a database called
taxidataalready exists (this template does not create the database/tables — that's from Task 1). - Names the query
FaresOver100DollarsUS. - Outputs the query's reference once the stack is created.
Step 5.4 — Set Up AWS CLI Credentials (before running any aws command)
(Covered in detail earlier — summary here:)
-
On the lab page, click
i AWS Details→ expand AWS CLI → Show. -
Copy the
[default]credential block. -
In the IDE terminal, run:
nano /home/ec2-user/.aws/credentials -
Paste the credentials, replacing any old block.
-
Save:
Ctrl+X→Y→Enter. -
Verify:
aws sts get-caller-identityshould return your identity.
Step 5.5 — Validate the Template
aws cloudformation validate-template --template-body file://athenaquery.cf.ymlSuccess looks like:
{
"Parameters": []
}Don't proceed until this succeeds.
Step 5.6 — Create the CloudFormation Stack
aws cloudformation create-stack --stack-name athenaquery --template-body file://athenaquery.cf.ymlSuccess returns a Stack ARN:
{
"StackId": "arn:aws:cloudformation:us-east-1:338778555682:stack/athenaquery/2d8cec90-5c42-11ec-8fbf-12034b0079a5"
}🔎 To watch progress: open the CloudFormation console → Stacks, find
athenaquery, and check its status.
Step 5.7 — Confirm the Named Query Was Created
aws athena list-named-queriesExpected:
{
"NamedQueryIds": [
"644f6c10-bf57-48a2-a0ec-a3de179db511"
]
}Copy this ID somewhere safe.

62bb8a1d-6bbd-4fc0-95c7-55e77921ad39
Step 5.8 — Retrieve the Named Query's Details
aws athena get-named-query --named-query-id <QUERY-ID>aws athena get-named-query --named-query-id 62bb8a1d-6bbd-4fc0-95c7-55e77921ad39(Replace <QUERY-ID> with the ID from Step 5.7.)
Expected:
{
"NamedQuery": {
"Name": "FaresOver100DollarsUS",
"Description": "A query that selects all fares over $100.00 (US)",
"Database": "taxidata",
"QueryString": "SELECT distance, paytype, fare, tip, tolls, surcharge, total FROM yellow WHERE total >= 100.0 ORDER BY total DESC",
"NamedQueryId": "644f6c10-bf57-48a2-a0ec-a3de179db511",
"WorkGroup": "primary"
}
}Step 5.9 — Save the Query ID as a Bash Variable (for later tasks)
NQ=<QUERY-ID>NQ=62bb8a1d-6bbd-4fc0-95c7-55e77921ad39Confirm it saved correctly:
echo $NQShould print your query ID, e.g. 644f6c10-bf57-48a2-a0ec-a3de179db511.
✅ Task 5 summary: You turned a tested Athena query into a CloudFormation template, validated it, deployed it as a stack, and confirmed the named query exists — this is the reusable artifact other departments/accounts could deploy.
Task 6 — Reviewing the IAM Policy for Athena and AWS Glue Access
Goal: Understand exactly what permissions Mary has (least-privilege access), without creating any policy yourself (it's pre-created).
Step 6.1 — Open IAM
Search for and open IAM in the console.
Step 6.2 — Find Mary's User and Policy
- In the left nav, click Users.
- Note that
maryis listed — she's part of theDataScienceGroupIAM group. - Click
mary. - On the Permissions tab, click the
Policy-For-Data-Scientistslink. - Review the policy JSON/summary.
Step 6.3 — What This Policy Actually Grants
| Service | Permissions |
|---|---|
| Amazon S3 | Access buckets, list contents, read/write objects — cannot create a bucket |
| AWS Glue | Create databases and tables |
| CloudShell | Use CloudShell (e.g., run AWS CLI commands) |
| CloudFormation | Create stacks, validate templates |
| Athena | Create a Data Catalog, create/get named queries, start queries |
This is a least-privilege design — Mary can use Athena/Glue/CloudFormation for her work, but can't do things like create new S3 buckets or broader admin actions.
✅ Task 6 summary: You reviewed (didn't create) an IAM policy that scopes exactly what a data scientist can do across S3, Glue, Athena, and CloudFormation.
Task 7 — Confirming That Mary Can Access and Use the Named Query
Goal: Prove — by actually assuming her credentials — that Mary's IAM policy lets her retrieve the named query you built in Task 5.
Step 7.1 — Find the CloudFormation Stack With Mary's Credentials
- Search for and open CloudFormation.
- Click Stacks.
- Open the stack that built your lab environment (its name has a random string; it has the oldest creation time — not the
athenaquerystack you made in Task 5). - Go to the Outputs tab.
Step 7.2 — Copy Mary's Access Key
-
Copy the value of
MarysAccessKey. -
Back in the IDE terminal:
AK=<ACCESS-KEY>
AK=AKIAZ5MOW5TIAZPJPFNJAKIAZ5MOW5TIAZPJPFNJ
Step 7.3 — Copy Mary's Secret Access Key
-
Back in CloudFormation Outputs, copy
MarysSecretAccessKey. -
In the terminal:
SAK=<SECRET-ACCESS-KEY>
SAK=x+8ahXVtRKudEGykPInFUo6WzAg3nNnwbIPfj/Eax+8ahXVtRKudEGykPInFUo6WzAg3nNnwbIPfj/Ea
Step 7.4 — Run the Command As Mary
AWS_ACCESS_KEY_ID=$AK AWS_SECRET_ACCESS_KEY=$SAK aws athena get-named-query --named-query-id $NQThis prefixes the command with Mary's credentials as environment variables (instead of your own default profile), so AWS evaluates the request against her IAM permissions.
Expected output (same as Task 5's):
{
"NamedQuery": {
"Name": "FaresOver100DollarsUS",
"Description": "A query that selects all fares over $100.00 (US)",
"Database": "taxidata",
"QueryString": "SELECT distance, paytype, fare, tip, tolls, surcharge, total FROM yellow WHERE total >= 100.0 ORDER BY total DESC",
"NamedQueryId": "644f6c10-bf57-48a2-a0ec-a3de179db511",
"WorkGroup": "primary"
}
}If this succeeds, Mary's IAM policy correctly grants her access to the named query you deployed.
✅ Task 7 summary: You verified end-to-end that a restricted IAM user (Mary) — using only the permissions from Policy-For-Data-Scientists — can retrieve the Athena named query created via your CloudFormation stack.
Submitting Your Work
- At the top of the instructions, click Submit.
- Choose Yes when prompted.
- After a couple of minutes, a grades panel appears showing points per task.
- If it doesn't appear right away, click Grades at the top.
- Important: Some checks only grant credit if at least 5 minutes have passed since you completed that action. If a task shows 0 points on first submission, wait a few minutes and submit again — you can resubmit multiple times; only your last submission is recorded.
- For a breakdown, click Submission Report.
For Your Assignment Sheet
Take a screenshot showing:
- Your name (top-left profile icon in AWS Academy)
- The score panel (all task scores + total)
Ending the Lab
- At the top of the page, click ■ End Lab.
- Choose Yes to confirm.
- A message panel confirms the lab is terminating — click Close.
Full Task Summary Table
| Task | Concept | Key Technique |
|---|---|---|
| 1 | Schema-on-read basics | CREATE DATABASE, CREATE EXTERNAL TABLE, bulk add columns |
| 2 | Bucketizing (high cardinality) | Separate S3 file per subset → less data scanned |
| 3 | Partitioning (low cardinality) + Parquet | CREATE TABLE AS SELECT with format = 'PARQUET' |
| 4 | Views & CTEs | CREATE VIEW, WITH ... AS, JOIN |
| 5 | Infrastructure-as-code for queries | CloudFormation AWS::Athena::NamedQuery |
| 6 | Least-privilege IAM | Reviewing a scoped policy (not creating one) |
| 7 | Verifying access as another user | Overriding CLI credentials via env vars |
Additional Resources (from the lab)
- Amazon Athena Documentation
- Getting Started with AWS Glue
- Presto Documentation (Athena's underlying engine)
- Amazon Athena Pricing
- Using a SerDe
- Columnar Storage Formats
- Bucketing vs. Partitioning
- Working with Views in Athena
- Policies and Permissions in IAM
Guide compiled from the DES431 HW3 lecture slides and the full AWS Academy lab instructions (Dr. Apichon Witayangkurn, apichon@siit.tu.ac.th).