- SQLAlchemy Tutorial
- SQLAlchemy - Home
- SQLAlchemy - Introduction
- SQLAlchemy Core
- Expression Language
- Connecting to Database
- Creating Table
- SQL Expressions
- Executing Expression
- Selecting Rows
- Using Textual SQL
- Using Aliases
- Using UPDATE Expression
- Using DELETE Expression
- Using Multiple Tables
- Using Multiple Table Updates
- Parameter-Ordered Updates
- Multiple Table Deletes
- Using Joins
- Using Conjunctions
- Using Functions
- Using Set Operations
- SQLAlchemy ORM
- Declaring Mapping
- Creating Session
- Adding Objects
- Using Query
- Updating Objects
- Applying Filter
- Filter Operators
- Returning List and Scalars
- Textual SQL
- Building Relationship
- Working with Related Objects
- Working with Joins
- Common Relationship Operators
- Eager Loading
- Deleting Related Objects
- Many to Many Relationships
- Dialects
- SQLAlchemy Useful Resources
- SQLAlchemy - Quick Guide
- SQLAlchemy - Useful Resources
- SQLAlchemy - Discussion
Using DELETE Expression
In the previous chapter, we have understood what an Update expression does. The next expression that we are going to learn is Delete.
The delete operation can be achieved by running delete() method on target table object as given in the following statement −
stmt = students.delete()
In case of students table, the above line of code constructs a SQL expression as following −
'DELETE FROM students'
However, this will delete all rows in students table. Usually DELETE query is associated with a logical expression specified by WHERE clause. The following statement shows where parameter −
stmt = students.delete().where(students.c.id > 2)
The resultant SQL expression will have a bound parameter which will be substituted at runtime when the statement is executed.
'DELETE FROM students WHERE students.id > :id_1'
Following code example will delete those rows from students table having lastname as ‘Khanna’ −
from sqlalchemy.sql.expression import update from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String engine = create_engine('sqlite:///college.db', echo = True) meta = MetaData() students = Table( 'students', meta, Column('id', Integer, primary_key = True), Column('name', String), Column('lastname', String), ) conn = engine.connect() stmt = students.delete().where(students.c.lastname == 'Khanna') conn.execute(stmt) s = students.select() conn.execute(s).fetchall()
To verify the result, refresh the data view of students table in SQLiteStudio.