Delete multiple rows in SQLAlchemy
Delete multiple rows have a slightly different procedure than that of a conventional SQL query which is shown below
from sqlalchemy import delete
Tablename.delete().where(Tablename.c.column_name == value)
Get the books table from the Metadata object initialized while connecting to the database. Pass the delete query to the execute() function and get all the results using fetchall() function. Use a for loop to iterate through the results.
The SQLAlchemy query shown in the below code deletes the “non-fiction” genre this will effectively delete multiple rows at one go. Then, we can write a conventional SQL query and use fetchall() to print the results to check whether the table is updated properly.
Python3
# delete dele = BOOKS.delete().where(BOOKS.c.genre = = "non-fiction" ) engine.execute(dele) # write the SQL query inside the text() # block to fetch all records sql = text( "SELECT * from BOOKS" ) # Fetch all the records result = engine.execute(sql).fetchall() # View the records for record in result: print ( "\n" , record) |
Output:
Python SQLAlchemy – Delete Multiple Rows
In this article, we are going to see how to use the DELETE statement to delete multiple rows in SQLAlchemy against a PostgreSQL database in Python.
Contact Us