Python MySQL Delete Records

Remove unwanted data - clean up your database safely!

🗑️ Remove Old Data!

DELETE helps you remove records you don't need - like throwing away old papers!


import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="yourpassword",
  database="school"
)

cursor = mydb.cursor()
sql = "DELETE FROM students WHERE name = %s"
cursor.execute(sql, ("Old Student",))
mydb.commit()

print(f"✅ {cursor.rowcount} record deleted")
                                
DELETE
Command
Safe
Method
Clean
Database

What is DELETE?

DELETE removes unwanted records:

  • 🗑️ Remove Records - Delete specific rows from your table
  • 🎯 Targeted Removal - Delete only what matches your condition
  • 🔒 Permanent Action - Once deleted, data is gone forever
  • ⚠️ Use Carefully - Always double-check your conditions

Delete One Record

Delete a Specific Student

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="yourpassword",
  database="school"
)

cursor = mydb.cursor()

# Delete one specific student
sql = "DELETE FROM students WHERE name = %s"
name_to_delete = "John Smith"

cursor.execute(sql, (name_to_delete,))
mydb.commit()

print(f"✅ Deleted {cursor.rowcount} student record")

mydb.close()

⚠️ Important!

  • Always use WHERE clause - or you'll delete ALL records!
  • Use placeholders (%s) for safety
  • Don't forget commit() to save changes

Delete by Condition

Delete Students by Age

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="yourpassword",
  database="school"
)

cursor = mydb.cursor()

# Delete students older than 18
cursor.execute("DELETE FROM students WHERE age > %s", (18,))
mydb.commit()

if cursor.rowcount > 0:
    print(f"✅ Deleted {cursor.rowcount} students over 18")
else:
    print("❌ No students found over 18")

mydb.close()

Safe Delete Function

Delete with Confirmation

import mysql.connector

def safe_delete_student(student_name):
    """Safely delete a student with confirmation"""
    try:
        mydb = mysql.connector.connect(
            host="localhost",
            user="root",
            password="yourpassword",
            database="school"
        )
        
        cursor = mydb.cursor()
        
        # First, check if student exists
        cursor.execute("SELECT name, age FROM students WHERE name = %s", (student_name,))
        result = cursor.fetchone()
        
        if result:
            print(f"📋 Found: {result[0]} ({result[1]} years old)")
            
            # Delete the student
            cursor.execute("DELETE FROM students WHERE name = %s", (student_name,))
            mydb.commit()
            
            print(f"✅ {result[0]} has been deleted")
        else:
            print(f"❌ Student '{student_name}' not found")
        
        mydb.close()
        
    except mysql.connector.Error as error:
        print(f"❌ Error: {error}")

# Use the function
safe_delete_student("Alice Johnson")

Delete Multiple Records

Delete All Students from a Grade

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="yourpassword",
  database="school"
)

cursor = mydb.cursor()

# Delete all 12th grade students (graduated)
cursor.execute("DELETE FROM students WHERE grade = %s", ("12th",))
mydb.commit()

print(f"🎓 Deleted {cursor.rowcount} graduated students")

mydb.close()

Check Before Deleting

Preview What Will Be Deleted

import mysql.connector

def preview_delete(grade):
    """Show what will be deleted before actually deleting"""
    try:
        mydb = mysql.connector.connect(
            host="localhost",
            user="root",
            password="yourpassword",
            database="school"
        )
        
        cursor = mydb.cursor()
        
        # First, see what will be deleted
        cursor.execute("SELECT name, age FROM students WHERE grade = %s", (grade,))
        students_to_delete = cursor.fetchall()
        
        if students_to_delete:
            print(f"⚠️  These {len(students_to_delete)} students will be deleted:")
            for student in students_to_delete:
                print(f"  - {student[0]} ({student[1]} years old)")
                
            # Uncomment the next lines to actually delete
            # cursor.execute("DELETE FROM students WHERE grade = %s", (grade,))
            # mydb.commit()
            # print(f"✅ Deleted {cursor.rowcount} students")
        else:
            print(f"❌ No students found in {grade} grade")
        
        mydb.close()
        
    except mysql.connector.Error as error:
        print(f"❌ Error: {error}")

# Preview what will be deleted
preview_delete("12th")

DELETE Safety Tips

⚠️ Always Use WHERE

Without WHERE, you delete ALL records!

🔍 Check First

Use SELECT to see what you'll delete

🔒 Use Placeholders

Always use %s, never string formatting

💾 Commit to Save

Don't forget commit() to make it permanent

🧠 Test Your Knowledge

What happens if you forget WHERE in DELETE?

What must you do to save DELETE changes?