How to resolve SQLAlchemy Union Throwing Error

Question:

I’m using SQL Alchemy(Python, SQLServer) Union on two queries. It throws me the below error. Please help me in resolving it.

query1 = db.query(Employee.LastName).filter(Employee.Age == 30).all()
query2 = db.query(Employee.LastName).filter(Employee.Salary > 25000).all()
query3 = union(query1, query2).all()
**"SELECT construct for inclusion in UNION or other set construct expected, got [('Joseph',),('Alan',),('Joseph',)]."**

Also tried the below query and it throws the below error

query1 = db.query(Employee.LastName).filter(Employee.Age == 30).all()
query2 = db.query(Employee.LastName).filter(Employee.Salary > 25000).all()
query3 = query1.union(query2).all()
**"'list' object has no attribute 'union'"**
Asked By: Ra m

||

Answers:

Remove the .all() from the first two queries, it turns the queries into lists, but you want to pass Query instances to union.

query1 = db.query(Employee.LastName).filter(Employee.Age == 30) # <- Query
query2 = db.query(Employee.LastName).filter(Employee.Salary > 25000) # <- Query
result = query1.union(query2).all() # <- List
Answered By: snakecharmerb

For the above query, Can someone help me in using the order_by, I used the below query but it did not work

query1.union(query2).order_by(‘LastName’).all()

Answered By: Ra m
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.