SQLAlchemy Core
- Using Set Operations
- Using Functions
- Using Conjunctions
- Using Joins
- Multiple Table Deletes
- Parameter-Ordered Updates
- Using Multiple Table Updates
- Using Multiple Tables
- Using DELETE Expression
- Using UPDATE Expression
- Using Aliases
- Using Textual SQL
- Selecting Rows
- Executing Expression
- SQL Expressions
- Creating Table
- Connecting to Database
- Expression Language
SQLAlchemy ORM
- Dialects
- Many to Many Relationships
- Deleting Related Objects
- Eager Loading
- Common Relationship Operators
- Working with Joins
- Working with Related Objects
- Building Relationship
- Textual SQL
- Returning List and Scalars
- Filter Operators
- Applying Filter
- Updating Objects
- Using Query
- Adding Objects
- Creating Session
- Declaring Mapping
SQLAlchemy Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
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 pne 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( sqpte:///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.
Advertisements