Insert, update, delete

Draft

Reading rows is only half of SQL. This lesson changes data with INSERT, UPDATE, and DELETE, always using RETURNING so the result is visible.

Insert a row

INSERT adds a row. RETURNING shows the row PostgreSQL stored.

INSERT INTO users (name, email)
VALUES ('Edsger Dijkstra', 'edsger@example.com')
RETURNING *;
Loading plan...

Update a row

UPDATE changes matching rows. The WHERE clause keeps the change focused.

UPDATE users
SET active = false
WHERE email = 'alan@example.com'
RETURNING *;
Loading plan...

Delete a row

DELETE removes matching rows. RETURNING is useful when you want to inspect what was removed.

DELETE FROM users
WHERE email = 'grace@example.com'
RETURNING *;
Loading plan...

Try Yourself

Loaded Database:insert-update-delete.database-init

The database for this lesson is already loaded. Write any query you want and run it directly in your browser.

Exercises

0 OF 2 DONE
1.Insert Katherine Johnson with email katherine@nasa.gov and return the inserted row.
2.Set Ada Lovelace to inactive and return the updated row.

What We Learned

  • INSERTadds new rows to a table.
  • UPDATEchanges rows that match a WHERE clause.
  • DELETEremoves rows that match a WHERE clause.
  • RETURNINGturns writes into visible result rows.