Thuta Learning
SQL
IntermediateData & DatabasesBeginner

INSERT INTO

SQLLesson 1225 min

What you'll walk away with

  • Write a column list and matching VALUES, and predict what omitted columns receive
  • Insert several rows in one statement and explain what happens when one row fails
  • Get generated ids and default values back immediately with RETURNING
  • Handle duplicate keys with ON CONFLICT DO NOTHING or DO UPDATE

Explain it simply

Explain it simply

Think of a table as a ledger with column headings. INSERT INTO writes one new line into that ledger: "put these values into these columns". Saving a new user from a signup form, recording a new order and storing a contact-form message are all INSERTs.

Columns you do not fill get the default value defined when the table was created, or NULL when there is no default. Numbers such as a customer id are usually generated by the database itself.

Problem → Why → Solution

The problem: corrupted data without a single error

In a script that adds customers, a developer writes the VALUES in the order of the form fields instead of the order of the column list. All four columns are text, so PostgreSQL accepts the row without a word. A week later a report shows a customer called "Norway" based in a country called "Stavanger".

swapped-values.sql
INSERT INTO customers (customer_name, contact_name, city, country)
VALUES ('Norway', 'Cardinal Market', 'Tom B. Erichsen', 'Stavanger');
-- INSERT 0 1  (accepted: every value is valid text)

Why doesn't the database catch it?

INSERT pairs the first column in the list with the first value in VALUES; it never checks names or meaning. As long as the data types fit, only constraints (NOT NULL, CHECK, foreign keys) can catch a wrong order. That is why it pays to keep the column list visually aligned with the values, bind parameters by name in application code, and look at the inserted row with RETURNING.

Core concept: column list, VALUES and defaults

In INSERT INTO table (col_a, col_b) VALUES (value_a, value_b), the column list and the VALUES must have the same length and are paired by position. You may leave the column list out, but then you must supply every column of the table in its definition order. That is fragile: the day someone adds or reorders a column, every old INSERT either fails or silently goes wrong. Always write the column list.

Columns missing from the list receive their default: 'active' for status text NOT NULL DEFAULT 'active', or NULL when there is no default. Leaving out a NOT NULL column that has no default fails with "null value in column ... violates not-null constraint". You can also write the DEFAULT keyword directly inside VALUES. A GENERATED ALWAYS AS IDENTITY column such as customer_id is numbered by the database, and trying to supply your own value raises an error.

Separate several row tuples with commas after VALUES to insert many rows in a single round trip. A statement is atomic: if one row violates a constraint, none of the rows are inserted; there is no half-finished insert. Text values go in single quotes, and an apostrophe inside is doubled: 'Bon app'''. From application code, send values as parameters ($1, $2) instead of concatenating strings.

After an INSERT, psql prints a command tag such as INSERT 0 1: the 0 is a leftover slot for a legacy OID, and the last number is how many rows were inserted. PostgreSQL's RETURNING clause hands the inserted rows back like a SELECT, so you get generated ids and defaults without a second query.

Mental model: pair by position
  1. Pair columns and values by position
  2. Fill missing columns: default or NULL
  3. Check every constraint
  4. All pass: rows are written
  5. RETURNING hands rows back

If one row fails, the whole statement fails and nothing is written.

General pattern

sql
INSERT INTO table_name (column_a, column_b, column_c)
VALUES (value_a, value_b, DEFAULT),
       (value_a2, value_b2, value_c2)
ON CONFLICT (unique_column) DO NOTHING      -- optional, PostgreSQL
RETURNING id_column, column_c;             -- optional, PostgreSQL

After the column list, each row goes into its own pair of parentheses inside VALUES. The DEFAULT keyword asks for the column's default. ON CONFLICT and RETURNING are optional PostgreSQL clauses.

Example: add a customer and get its id back

In the customers table, customer_id is an identity column and status defaults to 'active'. Four customers already exist, so the new one gets id 5. The query fills four columns, leaves the id and status to the database, and asks for them back with RETURNING.

CREATE TABLE customers (
  customer_id   integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_name text NOT NULL,
  contact_name  text,
  city          text,
  country       text,
  status        text NOT NULL DEFAULT 'active'
);
INSERT INTO customers (customer_name, contact_name, city, country) VALUES
  ('Alfreds Futterkiste', 'Maria Anders',   'Berlin',      'Germany'),
  ('Ana Trujillo',        'Ana Trujillo',   'Mexico City', 'Mexico'),
  ('Antonio Moreno',      'Antonio Moreno', 'Mexico City', 'Mexico'),
  ('Around the Horn',     'Thomas Hardy',   'London',      'UK');
insert.sql
INSERT INTO customers (customer_name, contact_name, city, country)
VALUES ('Cardinal Market', 'Tom B. Erichsen', 'Stavanger', 'Norway')
RETURNING customer_id, customer_name, status;

Code breakdown

  1. Column listINSERT INTO customers (customer_name, contact_name, city, country)

    The four columns being filled are named explicitly. customer_id and status are absent, so the database supplies the next identity number and the default 'active'.

  2. VALUESVALUES ('Cardinal Market', 'Tom B. Erichsen', 'Stavanger', 'Norway')

    The four values pair with the column list by position: 'Cardinal Market' goes into customer_name and 'Norway' into country. Text is written in single quotes.

  3. RETURNINGRETURNING customer_id, customer_name, status;

    The inserted row comes back like a SELECT, showing id 5 and status 'active' immediately. Application code can use this id to redirect to the new customer's profile page.

  4. Command tagRETURNING

    After the result table psql prints INSERT 0 1, meaning one row was inserted.

You should see
 customer_id |  customer_name  | status
-------------+-----------------+--------
           5 | Cardinal Market | active
(1 row)

INSERT 0 1

Many rows, apostrophes and atomic inserts

The first statement adds two customers at once, and contact_name becomes NULL because it was not supplied. In the second statement the second row's customer_name is NULL, which breaks NOT NULL, so the first row, 'Corner Shop', is not inserted either.

multi-row.sql
INSERT INTO customers (customer_name, city, country) VALUES
  ('Bon app''',         'Marseille', 'France'),
  ('Chop-suey Chinese', 'Bern',      'Switzerland')
RETURNING customer_id, customer_name, contact_name;   -- ids 5 and 6

-- Fails as a whole: neither row is inserted
-- INSERT INTO customers (customer_name, country) VALUES
--   ('Corner Shop', 'Ireland'),
--   (NULL,          'Spain');

Identity numbers can have gaps

A failed INSERT may already have consumed identity numbers, and they are never reused, so gaps like 5, 6, 9 are normal. Do not use an identity column for numbers that must have no gaps, such as invoice numbers.

ON CONFLICT: when the key already exists

Inserting a value that already exists in a unique column such as sku fails with "duplicate key value violates unique constraint". PostgreSQL's ON CONFLICT lets you decide what happens instead: DO NOTHING skips the row, DO UPDATE changes the existing row (an upsert). EXCLUDED refers to the row you tried to insert. MySQL writes this as ON DUPLICATE KEY UPDATE, and SQL Server usually uses MERGE.

upsert.sql
-- KB-01 exists: skip silently, RETURNING gives 0 rows
INSERT INTO products (sku, name, price)
VALUES ('KB-01', 'Keyboard', 39.00)
ON CONFLICT (sku) DO NOTHING
RETURNING product_id;

-- KB-01 exists: update its price instead (stock stays 12)
INSERT INTO products (sku, name, price)
VALUES ('KB-01', 'Keyboard', 39.00)
ON CONFLICT (sku) DO UPDATE SET price = EXCLUDED.price
RETURNING product_id, sku, price, stock;

In real projects

Where this shows up in real projects

A signup API runs INSERT INTO users (email, password_hash) VALUES ($1, $2) RETURNING id, created_at and creates a session from the returned id. Because email has a unique constraint, even two simultaneous signups with the same email produce exactly one success; the other gets error code 23505 (unique_violation), which the backend turns into "this email is already registered". Checking first with SELECT and then inserting has a race condition, so relying on the constraint is the correct design.

In data import jobs, inserting thousands of CSV rows one statement at a time is slow because of the round trips. Batching hundreds of rows into a multi-row VALUES, or using PostgreSQL's COPY command, is many times faster. Jobs that sync product prices from a supplier feed every night use ON CONFLICT (sku) DO UPDATE to add new products and update existing ones in one pass.

Common mistakes

Common mistakes

1. Leaving out the column list

INSERT INTO customers VALUES (...) may work today, yet it breaks after a migration adds a column, because the value count no longer matches. In this table customer_id is GENERATED ALWAYS, so without a column list the first value is aimed at the id and fails immediately. Always write the column list.

2. Quoting text with double quotes

With VALUES ("Cardinal Market"), PostgreSQL reads "Cardinal Market" as a column name and reports that the column does not exist. In SQL, text values use single quotes ('...'); double quotes are for identifiers such as table and column names. Double an apostrophe inside text: ''.

3. Fetching the new id with MAX(id)

Running SELECT MAX(customer_id) FROM customers after the INSERT returns someone else's id if another user inserted in between. In PostgreSQL use RETURNING customer_id, which gives your own row's id in the same statement.

Best practices

Best practices

  • Always write the column list and keep it aligned with VALUES.
  • Send values from application code as parameters, never by concatenating strings.
  • Get generated ids and defaults with RETURNING.
  • Rely on unique constraints and ON CONFLICT rather than checking for duplicates with a SELECT first.

Mini challenge

Mini challenge: stock the product catalog

The products table already holds KB-01 Keyboard. Write two INSERT statements: the first adds three products in one go and returns their ids; the second upserts KB-01 with a new price of 39.00.

  • Insert Mouse (MS-01, 19.90, stock 30), Monitor (MN-27, 249.00, default stock) and USB-C Cable (CB-02, 8.50, stock 100) in one statement
  • Use the DEFAULT keyword for the Monitor's stock
  • The first statement returns product_id, sku and stock with RETURNING
  • The second statement must not fail and changes only KB-01's price (stock stays 12)
catalog.sql
CREATE TABLE products (
  product_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  sku        text NOT NULL UNIQUE,
  name       text NOT NULL,
  price      numeric(8, 2) NOT NULL,
  stock      integer NOT NULL DEFAULT 0
);
INSERT INTO products (sku, name, price, stock)
VALUES ('KB-01', 'Keyboard', 45.00, 12);

-- TODO 1: insert MS-01, MN-27 (default stock) and CB-02 in ONE statement
--         and return product_id, sku, stock
INSERT INTO products (sku, name, price, stock)
VALUES ;

-- TODO 2: insert KB-01 at 39.00; if the sku exists, update only its price

Expected: First statement: (2, MS-01, 30), (3, MN-27, 0), (4, CB-02, 100). Second statement: (1, KB-01, 39.00, 12), the existing row is updated rather than a new id created.

Show hint

Put each row in its own parentheses, separated by commas. For the upsert use ON CONFLICT (sku) DO UPDATE SET price = EXCLUDED.price.

Show solution
catalog.sql
INSERT INTO products (sku, name, price, stock) VALUES
  ('MS-01', 'Mouse',       19.90,  30),
  ('MN-27', 'Monitor',     249.00, DEFAULT),
  ('CB-02', 'USB-C Cable', 8.50,   100)
RETURNING product_id, sku, stock;

INSERT INTO products (sku, name, price)
VALUES ('KB-01', 'Keyboard', 39.00)
ON CONFLICT (sku) DO UPDATE SET price = EXCLUDED.price
RETURNING product_id, sku, price, stock;

Quick quiz 1 / 3

status is text NOT NULL DEFAULT 'active' and city is text with no default. If an INSERT omits both, what do they get?

Quick quiz 2 / 3

A VALUES list holds three rows and the third violates a unique constraint. What happens?

Quick quiz 3 / 3

In PostgreSQL, what is the reliable way to get the generated id of the customer you just inserted?

What to remember

  • The column list and VALUES pair by position; always write the column list.
  • Omitted columns get their default or NULL, and identity columns are filled by the database.
  • A multi-row INSERT is atomic: one failing row means nothing is inserted.
  • RETURNING (PostgreSQL) hands back the inserted rows immediately.
  • Handle duplicate keys with ON CONFLICT DO NOTHING or DO UPDATE.

PostgreSQL SQL Tutorial — PostgreSQL Global Development Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.