SQLSQL
BeginnerLesson 5 of 15

INSERT, UPDATE & DELETE – SQL

Inserting, changing, and deleting data – and why WHERE is vital.

INSERT adds rows. Always specify the column list, so the code stays stable when columns are added. Multiple rows can go into one statement (faster than many single ones).

INSERT INTO kunden (name, stadt, registriert) VALUES ('Finn', 'Köln', '2024-04-01');

INSERT INTO produkte (name, kategorie, preis) VALUES
  ('Tastatur', 'Elektronik', 45.00),
  ('Tee', 'Lebensmittel', 6.20);

-- insert from a query
INSERT INTO bestellungen (kunde_id, datum) SELECT id, '2024-05-01' FROM kunden WHERE stadt = 'Berlin';

UPDATE changes existing rows, DELETE removes them. Both affect all rows that WHERE matches – without WHERE, they hit the entire table.

UPDATE produkte SET preis = preis * 1.05 WHERE kategorie = 'Lebensmittel';
UPDATE kunden SET stadt = 'Bonn', registriert = '2024-04-02' WHERE id = 5;

DELETE FROM bestellungen WHERE status = 'storniert';
-- TRUNCATE TABLE tmp;   -- quickly empties a table (PostgreSQL/MySQL; SQLite: DELETE FROM tmp;)
WarningDELETE FROM kunden; without WHERE deletes all customers. A good routine: first check with a SELECT using the same WHERE condition, then run it inside a transaction and verify the row count before you say COMMIT.
TipExisting foreign keys protect you: a customer with orders cannot be deleted unless ON DELETE is CASCADE. In SQLite, foreign keys must be enabled per connection with PRAGMA foreign_keys = ON;.