Is there a way to build a Query
object in SQLAlchemy which will be the equivalent of:
SELECT * FROM (VALUES (1, 2, 3)) AS sq;
Not the best solution but it worked for me:
import sqlalchemy as sa
query = sa.select(['*']).select_from(sa.text("(VALUES (1,2,3)) as sq"))
connection.execute(query).fetchall()
Output: [(1, 2, 3)]
PS:
VALUES
with the aliased columns example:
import sqlalchemy as sa
query_cte = (
sa.select([sa.column('age'), sa.column('name')])
.select_from(sa.text("(VALUES (22, 'Bob'), (30, 'Julia')) as t (age, name)"))
).cte()
query_name = sa.select([query_cte.c.name])
connection.execute(query_name).fetchall()
Output: [('Bob',), ('Julia',)]
WARNING: This solution is good for simple values. Be careful with the special symbols or words, they should be properly escaped.