🐘 PostgreSQL Tutorial

INSERT INTO in PostgreSQL: Single Rows, Multiple Rows & RETURNING

Learn the INSERT INTO statement in PostgreSQL — inserting one row, multiple rows in a single statement, and getting the new row back with RETURNING.

INSERT INTO in PostgreSQL

INSERT INTO adds new rows to a table.

Inserting a Single Row

INSERT INTO employees (name, email, department, salary)
VALUES ('Rahul Gupta', 'rahul@gmail.com', 'Engineering', 65000);

Columns you omit fall back to their DEFAULT value, or NULL if no default is set.

Inserting Multiple Rows at Once

A single INSERT can add many rows — far more efficient than running one INSERT per row.

INSERT INTO employees (name, email, department, salary) VALUES
  ('Rajan Gupta', 'rajan@gmail.com', 'Sales', 42000),
  ('Kajal Gupta', 'kajal@gmail.com', 'HR', 38000),
  ('Prity Gupta', 'prityg@gmail.com', 'Support', 30000);

Inserting the Result of a Query

Copy rows from one table straight into another.

INSERT INTO archived_employees
SELECT * FROM employees WHERE department = 'Support';

RETURNING — Get the New Row Back

Especially useful for grabbing an auto-generated id right after insert, without a separate SELECT.

INSERT INTO employees (name, email)
VALUES ('Zaid Shaikh', 'zaid@gmail.com')
RETURNING id, name;
 id |    name
----+-------------
  7 | Zaid Shaikh

Common Errors & Troubleshooting

  • ERROR: null value in column "name" violates not-null constraint — you omitted a required column, or explicitly passed NULL for it; supply a real value.
  • ERROR: duplicate key value violates unique constraint — you're inserting a value that already exists in a unique/primary-key column — see the Upsert lesson if you actually want "insert, or update if it exists" behavior.
  • Column/value count mismatch — INSERT INTO employees (name, email) VALUES ('Rahul') errors because there are 2 columns listed but only 1 value provided; the counts must match exactly.

Key Takeaways

  • A single INSERT statement can take one row or a comma-separated list of many.
  • Omitted columns use their DEFAULT, or NULL if none is defined.
  • RETURNING hands back the inserted row(s) in the same round trip — no follow-up query needed.