Search code examples
pythonsqlalchemyunion

How to resolve SQLAlchemy Union Throwing Error


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

Solution

  • 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