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';
Advertisement728 x 90
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 passedNULLfor 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
INSERTstatement can take one row or a comma-separated list of many. - Omitted columns use their
DEFAULT, orNULLif none is defined. RETURNINGhands back the inserted row(s) in the same round trip — no follow-up query needed.
Advertisement320 x 100