Practice deleting single records, parameterized queries, bulk deletes using executemany(), table truncation, and conditional existence checks directly inside Google Colab.
We will use SQL DELETE to remove records from our database student table using mysql.connector.
We defined my_cursor and my_connect in our database connection guide. Remember that data-modifying statements require an explicit commit() to permanently save changes unless autocommit is enabled on your connection.
my_cursor = my_connect.cursor()
my_cursor.execute("DELETE FROM student WHERE id=25")
my_connect.commit()
print("Rows Deleted =", my_cursor.rowcount)
my_connect.close()
Output:
Rows Deleted = 1
We used rowcount to verify the number of records deleted from our student table.
If an error occurs (such as an incorrect column name or constraint violation), MySQL returns an error message. We can catch and display database errors using try-except exception blocks.
my_cursor = my_connect.cursor()
try:
my_cursor.execute("DELETE FROM student WHERE Class='Five'")
my_connect.commit()
print("Rows Deleted =", my_cursor.rowcount)
except mysql.connector.Error as my_error:
print(my_error)
my_connect.close()
Output:
Rows Deleted = 3
Placeholders (%s) should be used inside the SQL string while passing variables separately as a tuple or list. This standard practice prevents SQL injection attacks when handling untrusted user input.
my_cursor = my_connect.cursor()
try:
query = "DELETE FROM student WHERE Class=%s"
my_data = ('Six',)
my_cursor.execute(query, my_data)
my_connect.commit()
print("Rows Deleted =", my_cursor.rowcount)
except mysql.connector.Error as my_error:
print(my_error)
my_connect.close()
Output:
Rows Deleted = 7
my_cursor = my_connect.cursor()
try:
query = "DELETE FROM student WHERE id=%s"
my_data = (7,)
my_cursor.execute(query, my_data)
my_connect.commit()
print("Rows Deleted =", my_cursor.rowcount)
except mysql.connector.Error as my_error:
print(my_error)
my_connect.close()
Output:
Rows Deleted = 1
When deleting multiple distinct records in bulk, passing a list of parameter tuples to executemany() is significantly more efficient than running separate queries in a loop.
my_cursor = my_connect.cursor()
try:
query = "DELETE FROM student WHERE id=%s"
my_data = [(7,), (5,), (4,), (3,)]
my_cursor.executemany(query, my_data)
my_connect.commit()
print("Rows Deleted =", my_cursor.rowcount)
except mysql.connector.Error as my_error:
print(my_error)
my_connect.close()
Output:
Rows Deleted = 4
To remove all records from a table without dropping its structure, you can execute a DELETE FROM statement without a WHERE clause:
my_cursor = my_connect.cursor()
try:
query = "DELETE FROM student"
my_cursor.execute(query)
my_connect.commit()
print("Rows Deleted =", my_cursor.rowcount)
except mysql.connector.Error as my_error:
print(my_error)
my_connect.close()
Output:
Rows Deleted = 24
Alternatively, you can use the TRUNCATE TABLE command, which drops and recreates the table internally for high-speed clearing and resets auto-increment counters:
my_cursor = my_connect.cursor()
try:
query = "TRUNCATE student"
my_cursor.execute(query)
my_connect.commit()
print("Rows Deleted =", my_cursor.rowcount)
except mysql.connector.Error as my_error:
print(my_error)
my_connect.close()
Output:
Rows Deleted = 0
Before executing a delete statement, you can check if a matching record exists using a SELECT query combined with rowcount or conditional logic:
Using SQLAlchemy 2.0+:
from sqlalchemy import create_engine, text
engine = create_engine("mysql+mysqldb://userid:password@localhost/my_tutorial")
query = "SELECT id FROM student WHERE id=6"
with engine.begin() as conn:
result = conn.execute(text(query))
rows = result.fetchall()
if len(rows) > 0:
del_res = conn.execute(text("DELETE FROM student WHERE id=6"))
print("Rows Deleted =", del_res.rowcount)
else:
print("No matching record")
Using MySQL Connector:
import mysql.connector
my_connect = mysql.connector.connect(
host="localhost",
user="userid",
passwd="password",
database="my_tutorial"
)
####### end of connection ####
my_cursor = my_connect.cursor(buffered=True)
query = "SELECT id FROM student WHERE id=5"
my_cursor.execute(query)
if my_cursor.rowcount == 1:
my_cursor.execute("DELETE FROM student WHERE id=5")
my_connect.commit()
print("Rows Deleted =", my_cursor.rowcount)
else:
print("No matching record")
my_connect.close()
WHERE clause deletes all rows from the table. Always double-check your conditional clauses before executing write queries in production.
DELETE FROM is a Data Manipulation Language (DML) statement that removes rows individually, logs row deletions, fires triggers, and allows rollbacks within transactions. TRUNCATE TABLE is a Data Definition Language (DDL) operation that drops and recreates the table instantly, resetting auto-increment counters and performing an implicit commit.
DELETE, which scans and removes rows individually and reports counts, TRUNCATE TABLE resets the table structure at the storage engine level, returning 0 rows affected in MySQL connector responses.
mysql.connector, non-buffered cursors return -1 for rowcount on SELECT queries until all records are fetched. Using a buffered cursor (buffered=True) ensures the result set is downloaded immediately so rowcount` accurately reports matching records.
Learn how to completely delete tables, constraints, and databases using DROP queries.
Learn how to modify and update existing records in MySQL tables.
Understand how row counts behave across SELECT statements, updates, and deletes.
Download the complete student.sql database dump file featuring sample records with the gender column schema.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
15-07-2020 | |
| i want few modification while deleting record from MySQL table. if record doesn't exist then message will appear and if exists then delete that record and message will occur for successfully deletion. | |
18-07-2020 | |
| Check if record exists then delete. .. This part is added at the end now. Thanks | |