Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: How do you delete multiple rows without querying

I have a table that has millions of rows. I want to delete multiple rows via an in clause. However, using the code:

session.query(Users).filter(Users.id.in_(subquery....)).delete()

The above code will query the results, and then execute the delete. I don't want to do that. I want speed.

I want to be able to execute (yes I know about the session.execute):Delete from users where id in ()

So the Question: How can I get the best of two worlds, using the ORM? Can I do the delete without hard coding the query?

like image 993
supreme Pooba Avatar asked Sep 29 '16 14:09

supreme Pooba


3 Answers

Yep! You can call delete() on the table object with an associated where clause.

Something like this:

stmt = Users.__table__.delete().where(Users.id.in_(subquery...))

(and then don't forget to execute the statement: engine.execute(stmt))

source

like image 181
dizzyf Avatar answered Oct 15 '22 01:10

dizzyf


To complete dizzy's answer:

delete_q = Report.__table__.delete().where(Report.data == 'test')
db.session.execute(delete_q)
db.session.commit()
like image 43
Mickael Avatar answered Oct 14 '22 23:10

Mickael


The below solution also works, if developers do not want to execute a plain vanilla query.

session.query(Users).filter(Users.id.in_(subquery....)).delete(synchronize_session=False)
like image 44
Ojus sangoi Avatar answered Oct 15 '22 01:10

Ojus sangoi