This MySQL Delete lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
DELETE removes rows. A DELETE without WHERE removes every row in the table.
Write the WHERE first and read it twice. There is no undo unless you have a backup.
Example 1: Start here
DELETE FROM learner WHERE id = 2 is the statement. Keep the WHERE.
rows = [{"id": 1, "city": "Chennai"}, {"id": 2, "city": "Madurai"}] # a list; the values stay in this order
rows = [row for row in rows if row["id"] != 2] # a list; the values stay in this order
print(rows)
Example 2: Filter the rows
MySQL Delete is easier to see as a list of records. The filter keeps every row whose seats value is at least 10.
rows = [{"topic": "MySQL Delete", "seats": 16}, {"topic": "SQL", "seats": 12}] # a list; the values stay in this order
print([row["topic"] for row in rows if row["seats"] >= 10]) # keep the items that pass the test
Example 3: Update one field
An update changes one field and leaves the rest of the record alone. On a database you would run an UPDATE or an update_one for the same change.
row = {"topic": "MySQL Delete", "seats": 16} # a dictionary; each key has one value
row["seats"] = row["seats"] + 1 # change this one field
print(row)
Example 4: Count the matches
Counting matches is the idea behind COUNT(*). Here the number 16 appears twice.
rows = [16, 4, 16] # a list; the values stay in this order
print(sum(1 for value in rows if value == 16)) # keep the items that pass the test
