# Athena SQL notes and patterns

Read when writing SQL for an analytic question or an export filter. Athena engine v3 uses Trino
syntax. Every query below writes its result to the workgroup's output location, so each one runs
only after the user confirms it (see [overview.md](overview.md)).

## Syntax that differs from other engines

- Identifiers in double quotes (`"order-date"`), string literals in single quotes.
- Dates: `date_trunc('month', ts)`, `date_add('day', -30, current_date)`,
  `date_diff('day', start_ts, end_ts)`, `date_parse(s, '%Y-%m-%d')`, `from_iso8601_timestamp(s)`.
- Tables read through CSV SerDes (`OpenCSVSerde`) return every column as a string: cast before
  arithmetic or comparison, using `try_cast(col AS double)` so one bad value does not fail the query.
- Large-table cardinality and percentiles: `approx_distinct(col)`, `approx_percentile(col, 0.95)`.

## Cost

Athena bills for the bytes scanned.

- Filter on partition columns (shown as partition keys in the preview) whenever the question allows.
- Select only the columns the question needs.
- Add `LIMIT` to exploratory queries.

## Patterns

Latest row per key:

```sql
SELECT * FROM (
  SELECT t.*, row_number() OVER (PARTITION BY <key> ORDER BY <updated_col> DESC) AS rn
  FROM <database>.<table> t) WHERE rn = 1;
```

Top N per group:

```sql
SELECT * FROM (
  SELECT <group_col>, <item_col>, <metric>,
         rank() OVER (PARTITION BY <group_col> ORDER BY <metric> DESC) AS rnk
  FROM <database>.<table>) WHERE rnk <= <n>;
```

Over a per-period aggregate, ordered by `<period_col>`:

- Change against the previous period: `<metric> - lag(<metric>) OVER (ORDER BY <period_col>)`.
- Running total: `sum(<metric>) OVER (ORDER BY <period_col>)`.
- 7-row moving average:
  `avg(<metric>) OVER (ORDER BY <period_col> ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)`.

Share of a group total: `<metric> / sum(<metric>) OVER (PARTITION BY <group_col>)`.

Monthly cohort retention: assign each entity its first-activity month with
`min(date_trunc('month', <event_ts>))`, join back to activity, and count distinct entities per
cohort and `date_diff('month', cohort_month, activity_month)`.

Funnel: one row per entity with `max(CASE WHEN <event> = '<step>' THEN 1 ELSE 0 END)` per step,
then sum each step column.

## Checks before trusting a result

- Duplicate keys: `SELECT <key>, count(*) FROM <table> GROUP BY <key> HAVING count(*) > 1 LIMIT 20`.
- Join fan-out: compare `count(*)` of the joined result with `count(*)` of the driving table; a
  larger joined count means the join key is not unique on the other side.
