How can I write a query with pypika to generate the following SQL?
SELECT "x" FROM unnest(ARRAY[1,2,3]) as t("x")
The closest I can get to is this:
from pypika import PostgreSQLQuery, Array, CustomFunction
unnest = CustomFunction('unnest', ['array'])
PostgreSQLQuery.from_(unnest(Array(1,2,3))).select('x')
Which outputs:
SELECT "x" FROM unnest(ARRAY[1,2,3])
But is obviously missing the required alias to allow me to use "x" in a following sub-query.
I am using Athena/Presto as the backend, but Postgres supports the same SQL
You can try using
Unnestclass from this comment @github which hacksAliasedQuery:And your case can look like:
Which generates:
Which is executed fine by Presto/Trino. But I would argue that this a workaround at best.