ప్రధాన కంటెంట్‌కు వెళ్లండి
eLearner.app
మాడ్యూల్ 8 · 4లో పాఠం 1కోర్సులో 29/57~10 min
మాడ్యూల్ పాఠాలు (1/4)

డేటాను చొప్పించడం: 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

SQL
INSERT INTO tabella (col1, col2, …)
VALUES (val1, val2, …);

Example on our dataset:

SQL
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:

SQL
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:

SQL
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 NULL without a DEFAULT → error;
  • if it has a DEFAULT (including SERIAL for id) → that is used;
  • if it accepts NULL → it becomes NULL.
SQL
-- 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

వ్యాయామం#sql.m8.l1.e1
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

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.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

The order of the values in VALUES must match the order of the columns you named.

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది

Review exercise

వ్యాయామం#sql.m8.l1.e2
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

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.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

RETURNING accepts a list of columns (or '*') exactly like a SELECT.

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది