Adding, changing and removing rows

INSERT, UPDATE and DELETE, and how to use them safely.

A real PostgreSQL database runs inside your browser tab. Nothing to install.

INSERT adds a row

INSERT INTO names the table and the columns you are filling. VALUES gives one value for each column, in the same order.

The id column fills itself in, so you leave it out. The email column may be left empty; the others may not.

Each run here starts again from the same eight students, so you can experiment freely.

Example
INSERT INTO students (name, city, marks) VALUES ('Isha', 'Jaipur', 70);
SELECT * FROM students;

Your turn: add a student

This time the table itself is checked after your statement runs.

Practice task

Add a student named Jatin who lives in Kochi and has 65 marks.

Your answer is run and checked in the lesson. Create a free account to try it.

UPDATE changes rows

UPDATE names the table, SET gives the new value, and WHERE chooses which rows to change.

Leave out WHERE and every row is changed. This is one of the most common and most costly mistakes in SQL, so write the WHERE first.

Example
UPDATE students SET city = 'Bengaluru' WHERE name = 'Harsh';
SELECT name, city FROM students;

Your turn: change one row

Only one student should change.

Practice task

Change Dev's marks to 58.

Your answer is run and checked in the lesson. Create a free account to try it.

DELETE removes rows

DELETE FROM removes the rows that match WHERE. As with UPDATE, leaving out WHERE affects every row.

PostgreSQL can show you what a change touched. Add RETURNING * to an INSERT, UPDATE or DELETE and it hands back the affected rows.

Example
DELETE FROM students WHERE marks < 60 RETURNING *;

Your turn: remove one row

Seven students should remain.

Practice task

Delete the student whose id is 7.

Your answer is run and checked in the lesson. Create a free account to try it.