SQL / MySQL Intermediate Queries · 7 min read

INSERT and UPDATE Rows with an Explicit WHERE

Lesson 4 of 33 in the SQL / MySQL learning path.

How do I insert a user and update that same row safely?

Registration writes a new student, and a later profile edit changes that same row. SQL splits those actions into INSERT and UPDATE. The insert names the columns and supplies one tuple. The update sets the new name and email and limits the write with WHERE id = 2, so Ada and Alan stay exactly as they were. A write that names the table and forgets the row is how a registrar empties or rewrites the whole account list.

The script uses literal values so you can run it in the mysql client and see one changed row. Application code must not concatenate form input into that statement. It should send the id and the new values through PDO placeholders, which is the pattern in php-pdo-insert and php-pdo-update. The form that posts the edit is the concern of html-get-vs-post-forms.

Syntax & Parameters

Syntax
INSERT INTO table_name (column_list)
VALUES (value_list);

UPDATE table_name
SET column_name = value
WHERE id = ?;

Example

queries.sql
CREATE DATABASE IF NOT EXISTS school
  CHARACTER SET utf8mb4
  COLLATE utf8mb4_unicode_ci;

USE school;

DROP TABLE IF EXISTS enrollments;
DROP TABLE IF EXISTS courses;
DROP TABLE IF EXISTS users;

CREATE TABLE users (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  name VARCHAR(120) NOT NULL,
  email VARCHAR(254) NOT NULL,
  password_hash VARCHAR(255) NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_users_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO users (name, email, password_hash, created_at)
VALUES ('Ada Lovelace', 'ada@school.test', 'sample-hash-not-a-secret', '2026-01-15 09:00:00');

INSERT INTO users (name, email, password_hash, created_at)
VALUES ('Grace Hopper', 'grace@school.test', 'sample-hash-not-a-secret', '2026-02-11 09:30:00');

INSERT INTO users (name, email, password_hash, created_at)
VALUES ('Alan Turing', 'alan@school.test', 'sample-hash-not-a-secret', '2026-03-02 11:00:00');

SELECT id, name, email, created_at
FROM users
WHERE id = 2;

UPDATE users
SET name = 'Grace Brewster Hopper',
    email = 'grace.hopper@school.test'
WHERE id = 2;

SELECT ROW_COUNT() AS updated_rows;

SELECT id, name, email, created_at
FROM users
ORDER BY id;

Expected Output

Before the update
id | name         | email             | created_at
2  | Grace Hopper | grace@school.test | 2026-02-11 09:30:00
1 row in set

updated_rows
1
1 row in set

After the update
id | name                   | email                      | created_at
1  | Ada Lovelace           | ada@school.test            | 2026-01-15 09:00:00
2  | Grace Brewster Hopper  | grace.hopper@school.test   | 2026-02-11 09:30:00
3  | Alan Turing            | alan@school.test           | 2026-03-02 11:00:00
3 rows in set

Line-by-Line Walkthrough

  1. The script creates school and users, then inserts Ada, Grace, and Alan so the update has a real target and two neighbors that must stay unchanged.
  2. Grace is the second insert, so her primary key is 2 on this empty table. The following statements use that id.
  3. The SELECT before the change reads id, name, email, and created_at for id 2 and shows the original name Grace Hopper.
  4. UPDATE users sets the legal name and the new email. The column list is explicit, and password_hash and created_at are left alone.
  5. WHERE id = 2 limits the write to one row. Ada and Alan do not match, so their names and emails stay as inserted.
  6. The literals 2, the name, and the email make the script runnable in the mysql client. Application code must pass those values as PDO placeholders, as shown in php-pdo-insert and php-pdo-update.
  7. SELECT ROW_COUNT() immediately after the UPDATE reports how many rows changed. A following SELECT would replace that figure with its own row count, so the count runs first.
  8. The final SELECT lists every user. Only id 2 shows Grace Brewster Hopper and grace.hopper@school.test.
  9. created_at remains 2026-02-11 09:30:00 because the UPDATE did not assign that column.
  10. A second run of the same UPDATE still matches one row. If the values are already current, MySQL reports 0 rows changed and the data stays correct.

Common Pitfalls & Security

INSERT adds a row. UPDATE changes rows that already exist. The dangerous form is an UPDATE that names users and sets columns and has no WHERE clause. MySQL then applies the new name and email to every student, and a commit makes that damage permanent. Always name the primary key or another unique predicate. The sample changes only id 2.

  • An UPDATE without WHERE is a catastrophe. It rewrites every account in users. There is no undo unless you still have a backup or an open transaction you can roll back.
  • Building the statement by gluing a form field into the SQL text lets a crafted name change the statement. Application code must bind the name, email, and id with PDO placeholders.
  • Changing email to an address that another student already owns raises error 1062 and leaves the row as it was. Read that error and keep the old address.
  • ROW_COUNT() describes the previous statement. Run it immediately after the UPDATE. A SELECT in between replaces the count.
  • The sample hash is a stand-in string. A profile update that writes a typed password into password_hash stores a secret in the clear. Store a hash produced by the application.
  • WHERE id = 2 updates zero rows when that id is gone. Check the affected count before you tell the student the profile was saved.

Best Practices & Modern Standards

Insert with an explicit column list, then update that row with WHERE on the primary key. In application code the same shapes use PDO placeholders: the SQL text keeps a question mark where the sample uses a literal, and the driver sends the value separately. php-pdo-insert and php-pdo-update show that binding. A profile form should POST the edit, which is the point of html-get-vs-post-forms, so the new name is not left in a query string.

Read the affected-row count before you confirm the save. Keep created_at stable across profile edits, and set a separate updated time if the school needs to know when the row last changed. One statement should change one student unless you have deliberately selected a set.

Real-World Use

A registrar inserts a student into users when the person creates an account, then updates that same row when the student corrects a legal name or email. Courses and enrollments stay untouched because the WHERE clause names users.id. Staff tools must pass that id from the account being edited. A screen that saves a name onto every student record is a broken UPDATE, and it corrupts the enrollment roster that joins those users to courses.

Frequently Asked Questions

Why does the sample use literals if PHP should use placeholders?

This file is a mysql client script, so the id and the new email are written out and the statement can run alone. Application code must use PDO placeholders and bind the values, which is what php-pdo-insert and php-pdo-update demonstrate. The statement shape is the same.

How do I know the update changed Grace and nobody else?

WHERE id = 2 matches one primary key. The follow-up SELECT shows Ada and Alan unchanged and shows the new name only on id 2. ROW_COUNT() returns 1 when the name or email actually changed.

What if the new email is already used?

The UNIQUE key uq_users_email rejects the UPDATE with error 1062. Grace keeps her previous email. The application should report the conflict and leave the form values available for a correction.

Does the update change created_at?

No. The SET list names only name and email, so created_at stays 2026-02-11 09:30:00. Add a column to the SET list only when that column should change.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…