View a markdown version of this page

WITH clause (common table expressions) - Amazon Athena

WITH clause (common table expressions)

The WITH clause defines one or more common table expressions (CTEs): named subqueries that the main query, and the CTEs after them, can use like tables. Use CTEs to break a long query into named steps, or to use one subquery more than once.

Add RECURSIVE after WITH when a CTE needs to read its own rows. A recursive CTE has three parts: a starting query, then UNION or UNION ALL, then a recursive query that refers to the CTE by name. The recursive query runs on the rows that the previous step added, until it adds no rows. Use it to generate series or to walk hierarchies, such as an organization chart.

Syntax

WITH [ RECURSIVE ] cte_name [ ( column [, ...] ) ] AS ( select ) [, ...] select

Examples

For a description of the sample tables that the examples on this page use, see SELECT statement in DuckDB.

The following SQL query computes the total for each region in a CTE, and then filters the totals in the main query.

WITH regional AS ( SELECT region, sum(amount) AS revenue FROM sales_db.sales_parquet GROUP BY region ) SELECT region, revenue FROM regional WHERE revenue > 100 ORDER BY region

The query returns the following results.

region revenue

east

162.75

north

310.00

The following SQL query defines two CTEs. The second one reads from the first.

WITH east_orders AS ( SELECT customer, amount FROM sales_db.sales_parquet WHERE region = 'east' ), east_total AS ( SELECT sum(amount) AS total FROM east_orders ) SELECT e.customer, e.amount, t.total FROM east_orders AS e, east_total AS t ORDER BY e.customer

The query returns the following results.

customer amount total

alice

120.50

162.75

carol

42.25

162.75

frank

NULL

162.75

The following SQL query uses a recursive CTE to generate the numbers 1 through 5.

WITH RECURSIVE numbers(n) AS ( SELECT 1 UNION ALL SELECT n + 1 FROM numbers WHERE n < 5 ) SELECT n FROM numbers ORDER BY n

The query returns the following results.

n

1

2

3

4

5

The following SQL query walks a reporting hierarchy, starting from the employee who has no manager. It returns the number of reporting levels between each employee and the top of the hierarchy.

WITH RECURSIVE employees(id, manager_id) AS (VALUES (1, NULL), (2, 1), (3, 2), (4, 2) ), chain(id, depth) AS ( SELECT id, 0 FROM employees WHERE manager_id IS NULL UNION ALL SELECT e.id, c.depth + 1 FROM employees AS e JOIN chain AS c ON e.manager_id = c.id ) SELECT id AS employee_id, depth FROM chain ORDER BY employee_id

The query returns the following results.

employee_id depth

1

0

2

1

3

2

4

2

Considerations

In a recursive CTE, give the recursive query a condition that eventually returns no rows, such as WHERE n < 5, so that the recursion ends.