SQL · Module 3 · Lesson 11 min read

INSERT & RETURNING

Basic INSERT

scss
INSERT INTO table_name (col1, col2) VALUES (val1, val2);
  • Always list the columns. It's clearer, and it keeps working if columns are added later.
  • Columns you skip get their DEFAULT (or NULL)
  • DEFAULT keyword: VALUES ('Lunch', DEFAULT)

Multiple rows at once

arduino
INSERT INTO t (a, b) VALUES (1, 'x'), (2, 'y'), (3, 'z');

Much faster than separate INSERTs.

INSERT … SELECT

Copy rows from a query: INSERT INTO archive (…) SELECT … FROM expenses WHERE …;

RETURNING (PostgreSQL) ⭐

Get values back from the inserted rows — no second query needed:

  • RETURNING id
  • RETURNING *
  • Works with UPDATE and DELETE too
  • Your app uses it to get the new id (Supabase does this with .select())

Values and quoting

  • Text and dates in single quotes: 'Lunch', '2026-11-24'
  • A single quote inside text is doubled: 'Hari''s bike'
  • Numbers and booleans without quotes: 250.50, true
  • Missing value: NULL (no quotes)
  • Arrays: '{essential,food}' or ARRAY['essential','food']

Common errors

  • Column count doesn't match the value count
  • Violating a constraint (NOT NULL, CHECK, UNIQUE, FK)
  • Wrong type: 'abc' into a NUMERIC column

⚠️ In app code, never build INSERTs by joining strings with user input → SQL injection (Unit 14). Use parameters.

Example

SQL
-- One row, listing the columns
INSERT INTO expenses (user_id, category_id, title, amount, spent_on)
VALUES (4, 7, 'Fruits', 640, '2026-11-12');

-- Multiple rows + get the generated ids back
INSERT INTO expenses (user_id, category_id, title, amount, spent_on, tags)
VALUES
  (2, 8, 'Hari''s birthday cake', 1500, '2026-11-12', '{social}'),
  (2, 2, 'Taxi', 380, '2026-11-13', ARRAY['work'])
RETURNING id, title, amount;
--  id |        title         | amount
--  33 | Hari's birthday cake | 1500.00
--  34 | Taxi                 |  380.00

-- Defaults fill the rest (spent_on = today, tags = '{}', created_at = now())
INSERT INTO expenses (user_id, title, amount)
VALUES (3, 'Coffee', 220)
RETURNING spent_on = CURRENT_DATE AS dated_today, tags;

-- INSERT ... SELECT: copy every unpaid bill into expenses
INSERT INTO expenses (user_id, category_id, title, amount, spent_on, tags)
SELECT user_id, 3, title || ' (bill)', amount, due_date, '{bill}'
FROM bills
WHERE NOT paid
RETURNING title, amount;

SELECT count(*) FROM expenses;   -- 31 original + 4 + 4 = 39