Home / AWS

AWSTroubleshootingAdvanced

Amazon Athena query failed or returned zero rows: HIVE_BAD_DATA, output location access denied, missing partitions and exhausted resources

Read Athena's error category and type, then fix the usual failures - bad rows, schema mismatches, S3 and KMS permissions, Lake Formation, unloaded partitions, scan limits and resource exhaustion.

Deepak Bhardwaj7 min read

Applies toAmazon Athena (engine version 3), AWS Glue Data Catalog, Amazon S3, AWS Lake Formation, AWS CLI v2

Symptom

A scheduled report, a dashboard or an ad hoc query against your ALB, CloudTrail or application logs either ends in FAILED or SUCCEEDED with no rows. The console message is cut short, and running the query again gives the same result.

1. Get the full error, not the console summary

aws athena get-query-execution --query-execution-id <id> \
  --query "QueryExecution.{state:Status.State, reason:Status.StateChangeReason, err:Status.AthenaError, wg:WorkGroup, db:QueryExecutionContext.Database, out:ResultConfiguration.OutputLocation, scannedBytes:Statistics.DataScannedInBytes, engineMs:Statistics.EngineExecutionTimeInMillis, queueMs:Statistics.QueryQueueTimeInMillis}"

AthenaError contains ErrorCategory (1 = system, 2 = user, 3 = other), ErrorType and Retryable. Category 2 errors keep failing until you change the query, data or permissions, so don't just retry them.

To find recent failures in a workgroup:

for id in $(aws athena list-query-executions --work-group primary --max-items 50 \
            --query "QueryExecutionIds[]" --output text); do
  aws athena get-query-execution --query-execution-id "$id" \
    --query "QueryExecution.[QueryExecutionId,Status.State,Status.StateChangeReason]" --output text
done | grep FAILED

2. Map the message to the cause

Message contains Usual cause Fix
HIVE_BAD_DATA: Error parsing field value A row has a value that doesn't match the column type, for example text in an int column Find the file with "$path" (below) and fix the data or change the column type
HIVE_PARTITION_SCHEMA_MISMATCH The partition's schema in Glue is different from the table's Make the partition schemas match the table, or drop and re-add the partitions
HIVE_CURSOR_ERROR / HIVE_CANNOT_OPEN_SPLIT Corrupt or truncated file, an object in Glacier storage classes, S3 403 on one prefix, or S3 SlowDown Check the object named in the message (storage class, KMS key, permissions)
Access denied when writing output to url Caller can't s3:PutObject to the results location, or can't use its KMS key Fix IAM, the bucket policy or the key policy for the output location
No output location provided Workgroup has no result location and the client doesn't pass one Set OutputLocation on the workgroup
Insufficient Lake Formation permission(s) Table is governed by Lake Formation and the principal has no grant on it Grant SELECT (and DESCRIBE) in Lake Formation
TABLE_NOT_FOUND / SCHEMA_NOT_FOUND Wrong database, wrong Region, or the catalog is in another account Check QueryExecutionContext and the Region
Query exhausted resources at this scale factor Large ORDER BY without LIMIT, wide GROUP BY, DISTINCT on huge sets, or joins with the large table on the right Rewrite the query (section 5)
Bytes scanned limit was exceeded Workgroup BytesScannedCutoffPerQuery was reached Add partition filters or raise the cutoff deliberately
TooManyRequestsException / Rate exceeded Too many concurrent queries or API calls Spread scheduled jobs out, add backoff; check the current quotas

Exact message text varies between engine versions. Match on the error code at the start of the message.

3. Bad data: find the offending file

"$path" returns the S3 object each row came from. Use it to narrow down to one file:

-- List the files in the failing partition (run against a string-typed copy of the table if this also fails)
SELECT "$path", count(*) AS row_count
FROM app_logs
WHERE dt = '2026-11-19'
GROUP BY "$path"
ORDER BY row_count DESC;

-- Find values that won't cast, once the column is defined as string
SELECT "$path", status_code
FROM app_logs_raw
WHERE dt = '2026-11-19' AND try_cast(status_code AS integer) IS NULL
LIMIT 20;

If you can't fix the source, use a raw table with the column defined as string and try_cast it in a view. For JSON tables that use the OpenX SerDe, the 'ignore.malformed.json' = 'true' SerDe property skips malformed rows instead of failing the whole query.

Warning

ignore.malformed.json drops bad rows without any error. Use it for logs where a few lost lines don't matter, never for financial or audit data. Count the rows before and after you enable it.

For CSV files with a header row, add 'skip.header.line.count'='1' to TBLPROPERTIES. Otherwise the header row shows up as data, or fails to parse into typed columns.

4. Query SUCCEEDED with zero rows

This usually means the partitions aren't registered. The table exists, but Glue doesn't know about any new partition folders.

SHOW PARTITIONS app_logs;
Layout Fix
Hive-style folders (dt=2026-11-19/) MSCK REPAIR TABLE app_logs; works, but it is slow on large tables
Non-Hive folders (2026/11/19/) ALTER TABLE app_logs ADD IF NOT EXISTS PARTITION (dt='2026-11-19') LOCATION 's3://bucket/app/2026/11/19/';
Predictable date or number keys Use partition projection so you never have to load partitions

Partition projection for a daily layout:

ALTER TABLE app_logs SET TBLPROPERTIES (
  'projection.enabled'='true',
  'projection.dt.type'='date',
  'projection.dt.format'='yyyy/MM/dd',
  'projection.dt.range'='2024/01/01,NOW',
  'projection.dt.interval'='1',
  'projection.dt.interval.unit'='DAYS',
  'storage.location.template'='s3://bucket/app/${dt}/'
);

Other reasons a query returns zero rows:

  • The table LOCATION points to the wrong prefix. Check it with SHOW CREATE TABLE app_logs;.
  • The objects are in Glacier Flexible Retrieval or Deep Archive. Athena skips them or errors, depending on the table setting.
  • The WHERE clause compares a string partition with a date literal. Compare like with like (dt = '2026-11-19').

5. Exhausted resources and slow queries

Use the runtime statistics to see which stage is the expensive one:

aws athena get-query-runtime-statistics --query-execution-id <id> \
  --query "QueryRuntimeStatistics.{rows:Rows, timeline:Timeline}"

These rewrites fix most cases:

  • Add LIMIT to any ORDER BY over large results, or drop the sort.
  • Use approx_distinct(col) instead of count(DISTINCT col) when an estimate is good enough.
  • Put the largest table on the left of the join and filter both sides before joining.
  • Filter on partition columns first. A high QueryQueueTimeInMillis with low engine time means you are queuing for capacity, not that the query is slow.
  • Convert hot JSON or CSV data to partitioned Parquet with CREATE TABLE AS SELECT or INSERT INTO.

6. Permissions for the results location

The caller needs all of these, and any one missing gives Access denied even when the source data is readable:

# Where are results going, and can the workgroup settings be overridden by clients?
aws athena get-work-group --work-group primary \
  --query "WorkGroup.Configuration.{out:ResultConfiguration, enforce:EnforceWorkGroupConfiguration, cutoff:BytesScannedCutoffPerQuery, engine:EngineVersion.EffectiveEngineVersion}"
  • s3:GetBucketLocation, s3:ListBucket, s3:GetObject and s3:PutObject on the results bucket and prefix.
  • kms:GenerateDataKey and kms:Decrypt if results use SSE-KMS, and kms:Decrypt for source data encrypted with KMS.
  • glue:GetTable, glue:GetPartitions and glue:GetDatabase on the catalog objects.
  • If the source bucket is in another account, the bucket policy and the key policy there must allow your role.

If EnforceWorkGroupConfiguration is true, the client's own output location is ignored. Fix the workgroup's settings, not the client's.

Caution

Don't fix a results-bucket error by granting s3:* on *. Result files contain query output, often including log data that has personal or security-sensitive content. Scope access to the results prefix, and put a lifecycle rule on it.

Prevent it next time

  • Use partition projection for every log table with date-based paths, so no partitions have to be loaded.
  • Set BytesScannedCutoffPerQuery on shared workgroups and enforce the workgroup configuration.
  • Give scheduled jobs their own workgroup and alarm on failed queries. With publishing to CloudWatch turned on, Athena emits per-workgroup metrics.
  • Keep table DDL in source control, and test schema changes on a copy of the table first.
  • Land data as Parquet where you can. It fixes most HIVE_BAD_DATA problems at the source.