SQL INSERT, UPDATE and DELETE: Change Data Safely
Reading data is half of SQL. The other half changes it: adding new books, correcting prices, removing sold-out titles. Three statements do the work, and one habit keeps you safe: always know exactly which rows a change will touch.
INSERT
INSERT INTO books (title, author_id, genre, price, year, stock) VALUES (...); adds a row. List the columns explicitly, so the statement keeps working if the table gains a column, and so the values are matched to the right columns. Columns you leave out get their default value or NULL. Our id column is an INTEGER PRIMARY KEY, so SQLite assigns the next number automatically: the new book gets id 11. You can insert several rows at once by separating value lists with commas.
UPDATE
UPDATE books SET price = price - 2 WHERE genre = 'Tech'; changes every row that matches the WHERE clause. The new value can be an expression using the old values, as here. Set several columns with commas: SET price = 10, stock = 0.
Without a WHERE clause, UPDATE changes every row in the table. Before running an update, run a SELECT with the same WHERE to see which rows it will affect.
DELETE
DELETE FROM books WHERE stock = 0; removes matching rows; here it removes "River of Salt". As with UPDATE, leaving out WHERE deletes everything.
Expected output
id | title | price 2 | Northern Lights Code | 37.5 4 | Learning SQL by Doing | 27.0 7 | Small Data, Big Ideas | 32.99 11 | Tidal Patterns | 16.0 books_left 10
The example then queries the table to show the result: the Tech prices are 2 lower, the new book is present, and the count is back to 10 after one insert and one delete. In the in-browser runner, every run starts with a fresh copy of the sample database, so experiment freely.
Transactions
Wrap related changes in a transaction: BEGIN; ... COMMIT;. Either every statement in it takes effect, or, if you run ROLLBACK; instead of COMMIT; or something fails, none of them do. That protects you from half-finished changes, such as an order saved without its items. Many applications open a transaction for every request automatically.
RETURNING
SQLite 3.35 and later, like PostgreSQL, accept RETURNING at the end of INSERT, UPDATE and DELETE to show the affected rows, for example DELETE FROM books WHERE stock = 0 RETURNING title;.
Common mistakes
UPDATEorDELETEwithoutWHERE.- Relying on column order in
INSERT INTO books VALUES (...). - Inserting user input by building SQL strings; use parameterized queries in application code to prevent SQL injection.
Summary
INSERT INTO t (cols) VALUES (...)adds rows; list the columns.UPDATE t SET col = expr WHERE ...changes matching rows.DELETE FROM t WHERE ...removes matching rows.- Preview with
SELECT, and group related changes in a transaction.
Quiz: INSERT, UPDATE, DELETE