INSERT INTO SELECT and Loading Files
INSERT INTO table SELECT ... copies the rows a query returns into a table that already exists. It's how you fill a table from other tables: archiving old payments, saving monthly totals for a report, or copying cleaned rows out of a staging table. Its partner for data that lives outside the database, in a spreadsheet or a CSV file, is PostgreSQL's COPY. This lesson covers both, the column-matching rules that trip people up, and how to check that a load put in exactly the rows you expected.
In One Minute
INSERT INTO t (cols) SELECT ...inserts every row theSELECTreturns.- Columns match by position, not by name: list the target columns, and keep the order the same.
- Any
SELECTworks: withWHERE, joins,GROUP BY, and calculated columns. COPY table FROM 'file.csv'(server) and\copy(psql, your computer) load CSV files.- After a load, count the rows and compare with what you expected.
The Basics
INSERT INTO target_table (column1, column2, ...)
SELECT expression1, expression2, ...
FROM source_table
[WHERE ...];No VALUES keyword: the SELECT takes its place. Archiving the payments made before December 2025 into a table of their own:
CREATE TABLE payments_archive (
payment_id INTEGER PRIMARY KEY,
student_id INTEGER,
amount_usd NUMERIC(8,2),
paid_on DATE
);
INSERT INTO payments_archive (payment_id, student_id, amount_usd, paid_on)
SELECT payment_id, student_id, amount_usd, paid_on
FROM payments
WHERE paid_on < '2025-12-01';
SELECT * FROM payments_archive ORDER BY payment_id;CREATE TABLE
INSERT 0 3
payment_id | student_id | amount_usd | paid_on
------------+------------+------------+------------
1 | 101 | 450.00 | 2025-08-28
2 | 101 | 250.00 | 2025-10-30
6 | 103 | 225.00 | 2025-11-14
(3 rows)INSERT 0 3 reports three rows inserted: payments 1, 2 and 6, the ones before December. The original payments are untouched; INSERT ... SELECT copies, it doesn't move. To move rows, delete them from the source afterwards, inside a transaction, as Transactions shows.
Columns Match by Position
The first SELECT column goes into the first listed column, the second into the second, and so on, whatever their names. A SELECT with more columns than the target fails:
CREATE TABLE payments_archive (payment_id INTEGER, amount_usd NUMERIC(8,2));
INSERT INTO payments_archive
SELECT payment_id, amount_usd, paid_on FROM payments;CREATE TABLE
ERROR: INSERT has more expressions than target columnsWorse is a mismatch with compatible types, which succeeds and stores values in the wrong columns. Here the order is swapped, and only the type check catches it:
CREATE TABLE payments_archive (payment_id INTEGER, paid_on DATE, amount_usd NUMERIC(8,2));
INSERT INTO payments_archive
SELECT payment_id, amount_usd, paid_on FROM payments;CREATE TABLE
ERROR: column "paid_on" is of type date but expression is of type numeric
HINT: You will need to rewrite or cast the expression.Had both columns been numbers, the amounts and some other number would have silently traded places.
Saving the Results of a Summary
Any query can feed an INSERT, including one with GROUP BY. Monthly totals, saved for a report:
CREATE TABLE monthly_totals (
month DATE,
total_usd NUMERIC(10,2)
);
INSERT INTO monthly_totals (month, total_usd)
SELECT date_trunc('month', paid_on)::date, sum(amount_usd)
FROM payments
GROUP BY date_trunc('month', paid_on);
SELECT * FROM monthly_totals ORDER BY month;CREATE TABLE
INSERT 0 5
month | total_usd
------------+-----------
2025-08-01 | 450.00
2025-10-01 | 250.00
2025-11-01 | 225.00
2025-12-01 | 1025.00
2026-01-01 | 200.00
(5 rows)Five months, five rows. The saved totals don't update when new payments arrive; they're a snapshot. For totals that always reflect the latest data, use a view, covered in Views.
Loading a CSV File
COPY reads a CSV file straight into a table, much faster than one INSERT per row. Suppose Navika's study log was kept in a spreadsheet and saved as study_sessions.csv:
session_id,student_id,studied_on,minutes,topic
1,103,2026-01-03,45,JavaScript loops
2,103,2026-01-04,30,JavaScript arrays
3,101,2026-01-04,90,Java streamsIn psql, on your own computer, \copy reads the file from your machine and sends it to the server:
feetracker=# \copy study_sessions FROM 'study_sessions.csv' WITH (FORMAT csv, HEADER true)
COPY 3HEADER true skips the first line of column names. COPY 3 reports three rows loaded. The SQL command COPY study_sessions FROM '/path/study_sessions.csv' ... does the same, but reads the file from the database server's disk, and needs special privileges; \copy is what you'll usually want. Both are PostgreSQL only: MySQL uses LOAD DATA INFILE, and SQL Server BULK INSERT.
Try it runs inside your browser and can't read files from your computer, so practice \copy with your own PostgreSQL. In Try it, the same three rows can be loaded from a VALUES list, and checked the same way:
CREATE TABLE study_sessions (
session_id INTEGER,
student_id INTEGER,
studied_on DATE,
minutes INTEGER,
topic TEXT
);
INSERT INTO study_sessions (session_id, student_id, studied_on, minutes, topic)
SELECT * FROM (VALUES
(1, 103, DATE '2026-01-03', 45, 'JavaScript loops'),
(2, 103, DATE '2026-01-04', 30, 'JavaScript arrays'),
(3, 101, DATE '2026-01-04', 90, 'Java streams')
) AS csv_rows;
SELECT count(*) AS rows_loaded, sum(minutes) AS total_minutes FROM study_sessions;CREATE TABLE
INSERT 0 3
rows_loaded | total_minutes
-------------+---------------
3 | 165
(1 row)Common Mistakes
Leaving out the column list. Then the SELECT must match every table column in order. List the columns.
Columns in a different order. They match by position, not name.
Running a load twice. Every row is inserted again. Check counts, or use a primary key so duplicates are refused.
Expecting COPY to read your computer's files. It reads the server's disk. Use \copy in psql.
Interview Corner
How do you copy rows from one table into another existing table?
INSERT INTO target (col1, col2) SELECT col1, col2 FROM source WHERE .... The SELECT replaces VALUES, and every row it returns is inserted.
How are columns matched in INSERT INTO ... SELECT?
By position: the first selected expression goes into the first listed target column, and so on. Names don't matter.
How do you load a CSV file into PostgreSQL?
COPY table FROM 'path' WITH (FORMAT csv, HEADER true) reads a file on the server; psql's \copy reads a file on the client machine.
Practice
Challenge: Create a table late_payments with payment_id, student_id and days_late (all INTEGER), fill it with every payment made after its due date, and show it sorted by payment_id.
Show solution
CREATE TABLE late_payments (
payment_id INTEGER,
student_id INTEGER,
days_late INTEGER
);
INSERT INTO late_payments (payment_id, student_id, days_late)
SELECT payment_id, student_id, paid_on - due_on
FROM payments
WHERE paid_on > due_on;
SELECT * FROM late_payments ORDER BY payment_id;CREATE TABLE
INSERT 0 2
payment_id | student_id | days_late
------------+------------+-----------
3 | 101 | 2
7 | 103 | 4
(2 rows)Two late payments, 2 and 4 days late. The third column is calculated in the SELECT, which is fine: any expression can feed an insert.
Key Takeaways
| You want to | Write |
|---|---|
| Copy matching rows | INSERT INTO payments_archive (...) SELECT ... FROM payments WHERE paid_on < '2025-12-01' |
| Save a summary | INSERT INTO monthly_totals (month, total_usd) SELECT ..., sum(...) ... GROUP BY ... |
| Load a CSV in psql | \copy study_sessions FROM 'file.csv' WITH (FORMAT csv, HEADER true) |
Was this tutorial helpful?