Module lessons (1/4)
Inserting data: INSERT
So far you've been reading data. It's time to write some. INSERT is
the command that adds new rows to a table.
The basic syntax
INSERT INTO tabella (col1, col2, …)
VALUES (val1, val2, …);Example on our dataset:
INSERT INTO customers (first_name, last_name, email, city, country, signed_up_on)
VALUES ('Marco', 'Bianchi', 'marco.bianchi@example.com', 'Verona', 'Italia', '2025-07-15');Naming the columns is the recommended practice: it makes the query
robust against future schema changes (e.g. a new optional phone column
doesn't break anything) and self-documenting.
Multi-row INSERT
A single statement, multiple rows — much faster than N separate INSERTs:
INSERT INTO categories (name, parent_id) VALUES
('Gaming', 1),
('Smart Home', 1),
('Cucina vegana', 8);RETURNING: reading the values you just inserted
A clause characteristic of PostgreSQL: RETURNING returns the rows that
were just created. Extremely handy for retrieving the auto-generated id:
INSERT INTO categories (name, parent_id)
VALUES ('Gaming', 1)
RETURNING id, name;The output is a one-row table with id (assigned by SERIAL) and
name.
What happens if a column is missing
If you omit a column in the INSERT:
- if it is
NOT NULLwithout a DEFAULT → error; - if it has a
DEFAULT(includingSERIALfor id) → that is used; - if it accepts
NULL→ it becomesNULL.
-- Va bene: id è SERIAL (auto), country ha NOT NULL ma forniamo tutti i campi
INSERT INTO customers (first_name, last_name, email, city, country, signed_up_on)
VALUES ('Olivia', 'Marini', 'olivia.marini@example.com', 'Bari', 'Italia', '2025-07-20');
-- Errore: first_name è NOT NULL e non è fornito
INSERT INTO customers (last_name, email, city, country, signed_up_on)
VALUES ('Marini', 'olivia.marini@example.com', 'Bari', 'Italia', '2025-07-20');Your turn
Insert into the customers table a new customer with first_name 'Marco', last_name 'Bianchi', email 'marco.bianchi@example.com', city 'Verona', country 'Italia' and signed_up_on '2025-07-15'. Explicitly name all columns.
Show hint
The order of the values in VALUES must match the order of the columns you named.
Solution available after 3 attempts
Review exercise
Insert a new 'Gaming' category as a child of 'Elettronica' (id = 1). Use the RETURNING clause to return the id and name of the newly created category.
Show hint
RETURNING accepts a list of columns (or '*') exactly like a SELECT.
Solution available after 3 attempts