Home > Back-end >  How to resolve SQLAlchemy Union Throwing Error
How to resolve SQLAlchemy Union Throwing Error

Time:10-15

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'"**

CodePudding user response:

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

CodePudding user response:

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()

  • Related