2

I have a problem with query by ORM SQLAlchemy.

I need to write subquery like this

SELECT DISTINCT ON (e.type) e.type AS e_type, e.num AS e_num 
FROM e ORDER BY e.type

by ORM SQLAlchemy, but when I've used .subquery().alias("q") in my query, DISTINCT ON was compiled to DISTINCT. Why and how am I fix it?


Without .subquery():

db.session.query(E.type, E.num).distinct(E.type).order_by(E.type)

compile to

SELECT DISTINCT ON (e.type) e.type AS e_type, e.num AS e_num FROM e ORDER BY e.type

With .subquery():

db.session.query(E.type, E.num).distinct(E.type).order_by(E.type).subquery().alias("q")

compile to

SELECT DISTINCT e.type AS e_type, e.num AS e_num FROM e ORDER BY e.type
  • Could you tell a bit more about how you have compiled and verified the result? – Ilja Everilä Mar 03 '20 at 12:51
  • @IljaEverilä Well, I've seen query in debug watcher. For verify, I executed the simple SQL query `SELECT DISTINCT ON (e.type) e.type, e.num FROM e ORDER BY e.type` to database directly and got 50 rows, but in script query 78251 rows was got. – Ilya Petrov Mar 04 '20 at 07:18

0 Answers0