Inserting rows

Topic 1 of 5 in Changing data10 min readBeginnerFree course

Overview

So far you’ve only read data. Now it’s time to change it. This chapter covers the commands that write — INSERT, UPDATE, DELETE — along with upserts, transactions and bulk loading. They’re the commands applications run every time someone signs up, places an order or edits a profile.

Reminder: you can reset your copy of the shop at any time by running shop.sql again, so experiment freely. Every example in this lesson continues from the one before.

Inserting one row

INSERT INTO names the table and the columns you’re providing, then VALUES gives the values in the same order:

SQL
INSERT INTO categories (name)
VALUES ('Gifts');
Text
INSERT 0 1

INSERT 0 1 is PostgreSQL’s confirmation: one row inserted (the 0 is a historical leftover). Check it:

SQL
SELECT * FROM categories ORDER BY id;
Text
 id |    name     
----+-------------
  1 | Coffee
  2 | Tea
  3 | Equipment
  4 | Accessories
  5 | Gifts
(5 rows)

You didn’t provide an id, yet the new row has id 5. The id column is an identity column: the database numbers new rows automatically. Letting it do so is the normal practice — you rarely choose ids yourself.

Three ways to INSERT. One row: INSERT INTO categories (name) VALUES (‘Gifts’). Several rows: INSERT INTO products (name, category_id, price, stock) VALUES (‘Oolong Reserve’, 2, 16.50, 20), (‘Cold Brew Kit’, 3, 34.00, 8). From a query: INSERT INTO archived_orders (id, customer_id, ordered_at) SELECT id, customer_id, ordered_at FROM orders WHERE ordered_at < ‘2026-03-01’. List the columns you are filling; omitted columns get their DEFAULT, or NULL, and identity columns number themselves. Every constraint is checked: a missing NOT NULL value or an unknown category_id makes the whole statement fail.

Always list the columns

You can leave out the column list, in which case you must provide every column, in the table’s order:

SQL
INSERT INTO categories VALUES (6, 'Gifts');   -- works, but fragile

Don’t. If someone adds a column to the table or reorders them, the statement breaks — or worse, puts values in the wrong columns. Naming the columns makes the statement self-documenting and robust.

Inserting several rows

One INSERT can add many rows: separate the value lists with commas. It’s faster than separate statements, and either all rows go in or none do.

SQL
INSERT INTO products (name, category_id, price, stock)
VALUES ('Oolong Reserve', 2, 16.50, 20),
       ('Cold Brew Kit',  3, 34.00, 8);
Text
INSERT 0 2

Defaults and NULLs

Columns you leave out of the list get their default value — or NULL if they have none. products.stock defaults to 0, so a product added without stock starts at zero:

SQL
INSERT INTO products (name, category_id, price)
VALUES ('Tea Tin', 5, 6.00);

SELECT id, name, category_id, price, stock
FROM products
WHERE id > 12
ORDER BY id;
Text
INSERT 0 1
 id |      name      | category_id | price | stock 
----+----------------+-------------+-------+-------
 13 | Oolong Reserve |           2 | 16.50 |    20
 14 | Cold Brew Kit  |           3 | 34.00 |     8
 15 | Tea Tin        |           5 |  6.00 |     0
(3 rows)

You can also write the keyword DEFAULT in place of a value to ask for the default explicitly — useful when inserting several rows where only some have a value.

RETURNING: see what you inserted

When an application creates a customer, it needs the new customer’s id straight away — to create their first order, say. RETURNING hands back the inserted rows, like a SELECT attached to the INSERT:

SQL
INSERT INTO customers (first_name, last_name, email, city, country, signup_date)
VALUES ('Lena', 'Fischer', 'lena.fischer@example.com', 'Berlin', 'Germany', '2026-12-04')
RETURNING id, first_name, signup_date;
Text
 id | first_name | signup_date 
----+------------+-------------
 11 | Lena       | 2026-12-04
(1 row)

INSERT 0 1

RETURNING * returns every column, including defaults the database filled in. It’s PostgreSQL’s (and SQLite’s) answer to “what id did I just get?”; you’ll use it again with UPDATE and DELETE in a later lesson.

When an INSERT is refused

The database checks every constraint on every inserted row. Category names must be unique:

SQL
INSERT INTO categories (name) VALUES ('Tea');
Text
ERROR:  duplicate key value violates unique constraint "categories_name_key"
DETAIL:  Key (name)=(Tea) already exists.

Prices can’t be negative:

SQL
INSERT INTO products (name, price) VALUES ('Mystery Box', -5);
Text
ERROR:  new row for relation "products" violates check constraint "products_price_check"
DETAIL:  Failing row contains (16, Mystery Box, null, -5.00, 0).

An order must belong to a customer that exists:

SQL
INSERT INTO orders (customer_id, ordered_at, status)
VALUES (999, '2026-12-04 12:00', 'pending');
Text
ERROR:  insert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey"
DETAIL:  Key (customer_id)=(999) is not present in table "customers".

And a required value can’t be missing:

SQL
INSERT INTO customers (first_name, last_name) VALUES ('No', 'Email');
Text
ERROR:  null value in column "email" of relation "customers" violates not-null constraint
DETAIL:  Failing row contains (12, No, Email, null, null, null, null, null).

In every case nothing is inserted — not even the other rows of a multi-row INSERT. (One side effect is visible in the Failing row details: the rejected product was given id 16 before the check failed. Identity numbers used by failed inserts are never reused, so ids can have gaps — never assume they’re consecutive.) Each error message names the constraint and the offending value, which makes problems easy to track down. These guarantees are why the data in a database stays trustworthy no matter how many programs write to it; you’ll learn to define them yourself in Constraints and keys.

INSERT … SELECT: copying rows

Instead of VALUES, an INSERT can take the rows produced by a query. That’s how you archive, copy or transform data in bulk. First, a simple archive table (creating tables is covered properly in chapter 9):

SQL
CREATE TABLE archived_orders (
    id          integer PRIMARY KEY,
    customer_id integer,
    ordered_at  timestamp,
    archived_on date DEFAULT date '2026-12-04'
);
Text
CREATE TABLE

Now copy every order from the first two months into it:

SQL
INSERT INTO archived_orders (id, customer_id, ordered_at)
SELECT id, customer_id, ordered_at
FROM orders
WHERE ordered_at < '2026-03-01';

SELECT * FROM archived_orders ORDER BY id;
Text
INSERT 0 6
 id | customer_id |     ordered_at      | archived_on 
----+-------------+---------------------+-------------
  1 |           1 | 2026-01-05 09:14:00 | 2026-12-04
  2 |           2 | 2026-01-12 18:40:00 | 2026-12-04
  3 |           1 | 2026-01-28 07:55:00 | 2026-12-04
  4 |           3 | 2026-02-03 12:01:00 | 2026-12-04
  5 |           4 | 2026-02-14 20:22:00 | 2026-12-04
  6 |           5 | 2026-02-20 10:30:00 | 2026-12-04
(6 rows)

The SELECT can be as complex as you like — joins, aggregates, CTEs — as long as its columns line up with the column list of the INSERT.

Text, dates and quotes

A few details that trip people up:

  • Text and dates go in single quotes: 'Berlin', '2026-12-04'. Numbers don’t: 16.50.
  • To include a single quote in text, double it: 'O''Brien'.
  • NULL is written without quotes. 'NULL' is the four-letter text “NULL”.
  • In application code, never build an INSERT by gluing user input into the SQL string — use parameters. SQL from application code shows why, and how.

Tip: before a big INSERT … SELECT, run the SELECT on its own and check the rows. Once it’s right, put INSERT INTO … on top.

Exercise

A new customer's first order

Kofi Mensah from Accra, Ghana, signed up on 4 December 2026 with the email kofi.mensah@example.com (no phone) and immediately ordered 2 × Assam Breakfast (product 5) at 9.50 and 1 × Electric Kettle (product 10) at 59.90. Write three INSERT statements: the customer (use RETURNING id to see the new id, which will be 11); the order for customer 11, placed at 2026-12-04 10:00 with status 'pending' and a shipping fee of 7.50 (use RETURNING id, which will be 25); and both order items for order 25 in a single INSERT. Finish with a SELECT that shows order 25's items with product names, sorted by product id.

SQL
INSERT INTO customers (first_name, last_name, email, city, country, signup_date)
VALUES (___)
RETURNING id;

-- the order, then its two items, then check

Summary

  • INSERT INTO table (columns) VALUES (values) adds a row; always list the columns you're filling.
  • Columns you leave out get their DEFAULT (or NULL); identity columns such as id number themselves.
  • One INSERT can add many rows with several VALUES lists, or copy rows with INSERT … SELECT.
  • RETURNING gives back the inserted rows — the easiest way to learn a new row's generated id.
  • Every constraint is checked: a duplicate unique value, a failed CHECK or an unknown foreign key rejects the whole statement.