1

I am working on change my python code from db.engine.execute to proper SqlAlchmy manner, But I am stuck with a query having subquery with group_by and order_by.

select * from (select * from table1 where value='a' or value='b' or value='c' order by value1 ) as a group by value2;

Is it possible to write this query in sqlalchemy way ?

Harsh Sharma
  • 10,942
  • 2
  • 18
  • 29
  • Yes, but you should at least try doing it yourself first. The official documentation and StackOverflow both contain many examples of using subqueries in SQLAlchemy. If you then have some specific problem in writing the query, and cannot find an existing answer to it here, ask away. As to your query, having `ORDER BY` in a subquery is pointless and possibly ignored by DBMS, depending on optimizers etc. – Ilja Everilä Nov 28 '18 at 15:59
  • Come to think of it, are you using this in MySQL to fetch first/max/min/etc.-per-group type of results? There's a lengthy discussion about the validity of such here: https://stackoverflow.com/questions/12102200/get-records-with-max-value-for-each-group-of-grouped-sql-results. In short, you cannot trust it. – Ilja Everilä Nov 28 '18 at 16:46

0 Answers0