Database Queries: A First Look at SQL · Lesson 31 of 112

Database INSERT, UPDATE and DELETE

What you will learn

  • How to add rows with INSERT
  • How to change rows with UPDATE
  • How to remove rows with DELETE
  • Why WHERE is essential for UPDATE and DELETE
  • How constraints refuse bad changes

This lesson runs on the sample database you chose in lesson 4.1, and it changes the data in your browser's copy (not on the server). The examples build on each other from top to bottom, so run them in order. If something goes wrong, press Reset data at the top and start again.

1. INSERT

INSERT adds a row. Name the columns, then give the values in the same order. A column you leave out gets its default, or NULL if the table allows it:

INSERT INTO customers (first_name, last_name, email, city, country, joined_on)
VALUES ('Noor', 'Haque', 'noor.haque@example.com', 'Dhaka', 'Bangladesh', '2026-10-01');
INSERT INTO categories (name) VALUES ('Pets'), ('Books');
SELECT customer_id, first_name, last_name, phone FROM customers ORDER BY customer_id DESC LIMIT 2;
SELECT category_id, name FROM categories ORDER BY category_id DESC LIMIT 2;
customer_id  first_name  last_name  phone
-----------  ----------  ---------  ------------
        421  Noor        Haque      NULL
        420  Lara        Singh      +86 20854287
(2 rows)

category_id  name
-----------  -----
         12  Books
         11  Pets
(2 rows)
INSERT INTO branches (name, city) VALUES ('Lakeside', 'Accra');
INSERT INTO branches (name, city) VALUES ('Hillcrest', 'Leeds'), ('Bayview', 'Manila');
SELECT branch_id, name, city FROM branches ORDER BY branch_id DESC LIMIT 3;
branch_id  name       city
---------  ---------  ------
        9  Bayview    Manila
        8  Hillcrest  Leeds
        7  Lakeside   Accra
(3 rows)
INSERT INTO students (first_name, last_name, birth_date, enrolled_year, email)
VALUES ('Noor', 'Haque', '2011-05-17', 2026, 'noor.haque@student.example');
INSERT INTO departments (name, building) VALUES ('Sport', 'Gym'), ('Music', 'Studio 2');
SELECT student_id, first_name, last_name, guardian_name FROM students ORDER BY student_id DESC LIMIT 2;
SELECT department_id, name, building FROM departments ORDER BY department_id DESC LIMIT 2;
student_id  first_name  last_name  guardian_name
----------  ----------  ---------  -------------
       361  Noor        Haque      NULL
       360  Eva         Alvarez    Hugo Alvarez
(2 rows)

department_id  name   building
-------------  -----  --------
            8  Music  Studio 2
            7  Sport  Gym
(2 rows)

We did not give an id; the database chose the next one because the id is the table's primary key (lesson 2.4). One statement can add several rows at once. Columns we left out (such as the phone) are NULL. Always name the columns: it keeps working if columns are added later.

2. UPDATE

UPDATE changes values in existing rows. SET says what to change, WHERE says which rows. The result says how many rows were changed: checking it is a good habit, because if you expected 1 and got 0 or 100, something is wrong.

UPDATE products SET price = 3 WHERE name = 'Ceramic mug';
(1 row changed)

You can calculate with the old value, and change many rows at once:

UPDATE products SET price = ROUND(price * 2, 2) WHERE category_id = 5;
SELECT name, price FROM products WHERE category_id = 5 ORDER BY product_id;
name            price
--------------  -----
Notebook A5      64.9
Gel pens (10)    48.0
Sticky notes     15.3
Desk organiser   27.9
Highlighters    158.0
Paper clips      64.9
Wall planner     13.2
(7 rows)

Seven products belong to category 5 (Stationery), and all seven changed.

UPDATE customers SET risk_level = 'high' WHERE customer_id = 7;
(1 row changed)

You can change many rows at once. Cards that are still active but expire before 2027 are blocked:

UPDATE cards SET status = 'blocked' WHERE status = 'active' AND expires_on < '2027-01-01';
SELECT status, COUNT(*) AS cards FROM cards GROUP BY status ORDER BY status;
status   cards
-------  -----
active     183
blocked     27
expired     40
(3 rows)

(A real bank never changes a balance with UPDATE: it records a new ledger entry instead, so that the history stays complete.)

UPDATE courses SET credits = 5 WHERE code = 'MATH201';
(1 row changed)

You can change many rows at once. Students without a guardian name get a placeholder (lesson 4.2 showed IS NULL):

UPDATE students SET guardian_name = 'Not given' WHERE guardian_name IS NULL;
SELECT COUNT(*) AS not_given FROM students WHERE guardian_name = 'Not given';
not_given
---------
       39
(1 row)

3. DELETE

DELETE removes rows:

DELETE FROM categories WHERE name = 'Books';
SELECT category_id, name FROM categories ORDER BY category_id DESC LIMIT 2;
category_id  name
-----------  ----
         11  Pets
         10  Toys
(2 rows)
DELETE FROM branches WHERE name = 'Bayview';
SELECT branch_id, name FROM branches ORDER BY branch_id DESC LIMIT 2;
branch_id  name
---------  ---------
        8  Hillcrest
        7  Lakeside
(2 rows)
DELETE FROM departments WHERE name = 'Music';
SELECT department_id, name FROM departments ORDER BY department_id DESC LIMIT 2;
department_id  name
-------------  ---------
            7  Sport
            6  Computing
(2 rows)

4. Without WHERE, everything changes

UPDATE and DELETE with no WHERE apply to every row. To show it safely we use a transaction: BEGIN starts one, and ROLLBACK cancels everything done since (chapter 6 explains transactions properly). Run the first box, then look, then run ROLLBACK.

BEGIN;
UPDATE products SET price = 1;
(45 rows changed)

Every product now costs 1. (A price of 0 would have been refused by the CHECK (price > 0) rule on the column, but 1 passes the rule and is just as wrong.)

SELECT COUNT(*) AS products_at_1 FROM products WHERE price = 1;
products_at_1
-------------
           45
(1 row)

This is one of the most common database disasters. Undo it:

ROLLBACK;
SELECT COUNT(*) AS products_at_1 FROM products WHERE price = 1;
SELECT name, price FROM products ORDER BY product_id LIMIT 3;
products_at_1
-------------
            0
(1 row)

name              price
----------------  -----
Steel pan           6.6
Ceramic mug         3.0
Wooden spoon set   29.5
(3 rows)
BEGIN;
UPDATE accounts SET status = 'closed';
(450 rows changed)

Every account is now closed:

SELECT status, COUNT(*) AS accounts FROM accounts GROUP BY status;
status  accounts
------  --------
closed       450
(1 row)

This is one of the most common database disasters. Undo it:

ROLLBACK;
SELECT status, COUNT(*) AS accounts FROM accounts GROUP BY status ORDER BY status;
status  accounts
------  --------
closed        30
frozen        16
open         404
(3 rows)
BEGIN;
UPDATE enrollments SET grade = 0;
(1002 rows changed)

Every grade is now 0:

SELECT COUNT(*) AS zero_grades FROM enrollments WHERE grade = 0;
zero_grades
-----------
       1002
(1 row)

This is one of the most common database disasters. Undo it:

ROLLBACK;
SELECT COUNT(*) AS zero_grades FROM enrollments WHERE grade = 0;
SELECT ROUND(AVG(grade), 1) AS avg_grade FROM enrollments;
zero_grades
-----------
          0
(1 row)

avg_grade
---------
     71.3
(1 row)

Protect yourself: write the WHERE first, run it as a SELECT to see which rows it picks, and use transactions so you can undo a mistake.

5. The database can say no

Rules from the table (chapters 2 and 3) apply to every change. Each box below is meant to fail; read the message:

DELETE FROM customers WHERE customer_id = 279;
IntegrityError: FOREIGN KEY constraint failed
INSERT INTO orders (order_id, customer_id, order_date, status, ship_city) VALUES (99999, 99999, '2026-05-01', 'paid', 'Dhaka');
IntegrityError: FOREIGN KEY constraint failed
INSERT INTO products (sku, name, category_id, supplier_id, cost, added_on) VALUES ('SKU-9999', 'Tape', 5, 1, 1.0, '2026-10-01');
IntegrityError: NOT NULL constraint failed: products.price
UPDATE products SET price = -5 WHERE product_id = 1;
IntegrityError: CHECK constraint failed: price > 0
  • Customer 279 cannot be deleted: orders still point to them.
  • An order for customer 99999 is refused: no such customer exists.
  • A product without a price is refused: price is NOT NULL.
  • A negative price is refused by the CHECK rule on the column.
DELETE FROM customers WHERE customer_id = 77;
IntegrityError: FOREIGN KEY constraint failed
INSERT INTO accounts (customer_id, branch_id, account_type, opened_on, balance_cents) VALUES (1, 1, 'checking', '2026-10-01', -500);
IntegrityError: CHECK constraint failed: balance_cents >= 0
INSERT INTO transactions (account_id, txn_date, kind, amount_cents, balance_after) VALUES (1, '2026-10-01', 'refund', 500, 500);
IntegrityError: CHECK constraint failed: kind IN ('deposit', 'withdrawal', 'transfer_in', 'transfer_out', 'fee', 'interest')
INSERT INTO transfers (from_account, to_account, amount_cents, created_on, status) VALUES (5, 5, 100, '2026-10-01', 'done');
IntegrityError: CHECK constraint failed: from_account <> to_account
  • Customer 77 cannot be deleted: accounts still point to them.
  • A negative balance is refused by a CHECK rule.
  • A ledger entry of a kind the bank does not know (refund) is refused by a CHECK rule.
  • A transfer from an account to the same account is refused by a CHECK rule.
DELETE FROM courses WHERE code = 'MATH101';
IntegrityError: FOREIGN KEY constraint failed
INSERT INTO enrollments (student_id, section_id, enrolled_on, grade) VALUES (361, 1, '2026-01-10', 120);
IntegrityError: CHECK constraint failed: grade BETWEEN 0 AND 100
INSERT INTO courses (code, title, department_id, credits) VALUES ('MATH101', 'Again', 1, 3);
IntegrityError: UNIQUE constraint failed: courses.code
INSERT INTO enrollments (student_id, section_id, enrolled_on) VALUES (99999, 1, '2026-01-10');
IntegrityError: FOREIGN KEY constraint failed
  • The course cannot be deleted: sections still point to it.
  • A grade of 120 is refused by a CHECK rule (0 to 100).
  • A second course with the same code is refused: code is UNIQUE.
  • An enrollment for a student that does not exist is refused by the foreign key.

(SQLite checks foreign keys only after PRAGMA foreign_keys = ON, which the sample databases set. Whether other systems check them by default is something to confirm in their documentation.)

Worked example: a safe change

First look, then change, then check:

The shop raises all Kitchen items by 10%:

SELECT name, price FROM products WHERE category_id = 2 ORDER BY product_id;
UPDATE products SET price = ROUND(price * 1.1, 2) WHERE category_id = 2;
SELECT name, price FROM products WHERE category_id = 2 ORDER BY product_id;
name              price
----------------  -----
Steel pan           6.6
Ceramic mug         3.0
Wooden spoon set   29.5
Glass jar           5.4
Chopping board     26.4
Tea kettle         79.0
Lunch box          29.5
(7 rows)

name              price
----------------  -----
Steel pan          7.26
Ceramic mug         3.3
Wooden spoon set  32.45
Glass jar          5.94
Chopping board    29.04
Tea kettle         86.9
Lunch box         32.45
(7 rows)

A customer reports a stolen card, so the bank freezes that customer's open accounts:

SELECT account_id, status FROM accounts WHERE customer_id = 7 ORDER BY account_id;
UPDATE accounts SET status = 'frozen' WHERE customer_id = 7 AND status = 'open';
SELECT account_id, status FROM accounts WHERE customer_id = 7 ORDER BY account_id;
account_id  status
----------  ------
         4  closed
       141  open
       258  open
       387  open
(4 rows)

account_id  status
----------  ------
         4  closed
       141  frozen
       258  frozen
       387  frozen
(4 rows)

The school gives each two-credit Arts course one more credit:

SELECT code, credits FROM courses WHERE credits = 2 AND department_id = 5 ORDER BY code;
UPDATE courses SET credits = credits + 1 WHERE credits = 2 AND department_id = 5;
SELECT code, credits FROM courses WHERE department_id = 5 ORDER BY code;
code    credits
------  -------
ART101        2
ART201        2
ART202        2
(3 rows)

code    credits
------  -------
ART101        3
ART201        3
ART202        3
(3 rows)

Run the SELECT with the same WHERE first to see which rows will change, and compare the number you expect with the number the UPDATE reports. If it printed anything else, you would stop and investigate before saving the change. (All data is made up.)

Common mistakes

  • UPDATE/DELETE without WHERE. Every row changes.
  • Inserting without column names, which breaks when the table changes.
  • Not checking how many rows were affected.
  • Deleting rows that others still point to. The database refuses (good), or leaves broken links if rules are missing.
  • Changing data directly in a live database without a backup (chapter 8).

Key takeaways

  • INSERT adds, UPDATE changes, DELETE removes.
  • UPDATE and DELETE need a WHERE; test it with SELECT first.
  • Check how many rows were changed.
  • Constraints (keys, NOT NULL, CHECK) refuse bad changes.
  • Mistakes can be undone only if you use transactions or backups.

Practice

1. Write a statement that adds one new row to a table of your choice, naming the columns.

Show answer

INSERT INTO suppliers (name, country) VALUES ('Lakeside Goods', 'Ghana');

Show answer

INSERT INTO branches (name, city) VALUES ('Garden', 'Lagos');

Show answer

INSERT INTO departments (name, building) VALUES ('Health', 'South Hall');

2. Write a statement that changes one value in exactly one row.

Show answer

UPDATE products SET price = 5 WHERE name = 'Ceramic mug';

Show answer

UPDATE customers SET city = 'Lisbon' WHERE customer_id = 12;

Show answer

UPDATE courses SET title = 'Algebra' WHERE code = 'MATH101';

3. What happens with DELETE FROM some_table;?

Show answer

Every row of the table is deleted, because there is no WHERE.

4. Why check how many rows an UPDATE changed?

Show answer

To see whether the number of changed rows is what you expected.

5. Why was deleting a customer, or a course, refused in section 5?

Show answer

Other rows still reference it through a foreign key, and the foreign key rule forbids leaving rows that point to something that does not exist.

6. How can you preview which rows an UPDATE will change?

Show answer

Run a SELECT with the same WHERE condition first.