Skip to content

Changing data without regret

UPDATE and DELETE do exactly what you asked, including when you asked for everything.

Lesson 4 of 4 · about 2 minutes

A missing WHERE changes every row

UPDATE students SET city = 'Pune' with no WHERE sets every student's city to Pune. So does DELETE FROM students delete all of them. Neither is a mistake the database can catch for you: both are valid, and both are sometimes what people mean.

The habit that prevents it costs nothing. Write the statement as a SELECT first with the same WHERE, look at the rows it returns, and only then change SELECT ... to UPDATE ... SET or DELETE. What you are checking is not the syntax but the row count.

Transactions, and what they are actually for

BEGIN starts a transaction; COMMIT makes the changes permanent; ROLLBACK discards them. Inside one, you can run the statement, check the result, and undo it if it was not what you meant.

The deeper purpose is that several statements either all happen or none do. Moving money between accounts is two updates, and a failure between them must not leave the money nowhere. That is what a transaction guarantees, and it is why "it worked on my machine" is not enough for anything involving more than one write.

Never build SQL by joining strings

Putting a value into a query by concatenation — "... WHERE name = '" + input + "'" — is SQL injection, and it is still the most damaging web vulnerability there is. A value containing a quote ends the string early and the rest is executed as code.

Parameters are the fix, and they are simpler than the thing they replace: WHERE name = ? or WHERE name = $1, with the value passed separately. The database then treats it as data no matter what it contains. Escaping by hand is not an equivalent — it is a smaller version of the same mistake.

Worked examples

  • Check before you change

    /SELECT * FROM students WHERE city = 'Pue'/

    Against: Run this before turning it into an UPDATE

    The typo returns zero rows, which tells you now rather than after you have updated nothing — or everything.

Check yourself

Practice questions written for this lesson — not past exam papers.

Practise every question in this subject

  1. What does UPDATE students SET city = 'Pune' do without a WHERE?

  2. What actually prevents SQL injection?