Sub topic 3
Copying rows with INSERT ... SELECT
This chapter assumes you can write a basic SELECT with a WHERE clause, know the Oracle data types NUMBER, VARCHAR2 and DATE, and understand primary key, foreign key and NOT NULL constraints. It also assumes you have run the setup script that creates dept_demo, emp_demo, emp_stage and emp_archive, and that you can run SQL in SQL*Plus, SQL Developer or SQLcl.
What INSERT ... SELECT does
INSERT ... VALUES adds one row whose values you type into the statement. INSERT ... SELECT replaces the VALUES list with a query. Every row the query returns becomes a new row in the target table, and the whole copy runs as one statement.
Use it to:
- Archive rows from a live table into a history table.
- Load a staging table into a production table.
- Build test data from existing data.
- Reshape rows, because the query can join, filter, aggregate and compute.
The basic form is:
INSERT INTO target_table (col1, col2, col3)
SELECT expr1, expr2, expr3
FROM source_table
WHERE condition;The query is an ordinary SELECT. Anything that works in a query works here, including joins, GROUP BY, analytic functions and subqueries.
A worked example
The archive example from the setup copies every inactive employee into emp_archive:
INSERT INTO emp_archive (emp_id, emp_name, dept_id, salary, status)
SELECT emp_id, emp_name, dept_id, salary, status
FROM emp_demo
WHERE status = 'INACTIVE';Oracle runs the SELECT, then inserts each returned row into emp_archive. With the sample data from the previous chapter, Grace is the only inactive employee, so one row is inserted. SQL*Plus and SQLcl report 1 row created. The rows are not permanent until you commit. Other sessions cannot see them, and you can still undo them with ROLLBACK.
The statement copies the rows and leaves the source untouched. emp_demo still contains Grace. A later DELETE removes her, which is the pattern the DELETE chapter uses: copy first, then delete only rows that are confirmed to be in the archive.
How columns are matched
Oracle matches columns by position, not by name. The first expression in the SELECT list goes into the first column in the INSERT column list, the second into the second, and so on.
-- Same names, wrong order: values land in the wrong columns
INSERT INTO emp_archive (emp_id, emp_name, dept_id, salary, status)
SELECT emp_id, emp_name, salary, dept_id, status
FROM emp_demo;This statement runs without error if the types are compatible, because salary and dept_id are both NUMBER. Salaries end up in the department column and the reverse. The data is silently wrong, which is worse than an error.
Rules to keep in mind:
- The number of expressions must equal the number of listed columns. A mismatch raises ORA-00913 (too many values) or ORA-00947 (not enough values).
- Each expression must be convertible to the type of its target column. A failed conversion raises an error such as ORA-01722 (invalid number) or ORA-01861 (literal does not match format string).
- Column names or aliases in the SELECT list do not matter. Only position matters.
Always list the columns
You can leave out the column list. Oracle then expects one value for every column of the target table, in table-definition order:
INSERT INTO emp_archive
SELECT * FROM emp_demo WHERE status = 'INACTIVE';This works only while both tables have the same columns in the same order. If someone adds a column to either table, the statement breaks or, worse, shifts values into the wrong columns. Naming the columns makes the statement survive schema changes and makes it readable. Reserve the short form for throwaway scripts.
A listed-column insert also lets you skip columns. Skipped columns take their DEFAULT, or NULL if there is no default. If a skipped column is NOT NULL and has no default, the statement fails with ORA-01400.
-- status is omitted, so each new row gets the default 'ACTIVE'
INSERT INTO emp_stage (emp_id, emp_name, dept_id, salary)
SELECT emp_id, emp_name, dept_id, salary
FROM emp_demo
WHERE dept_id = 20;Computing and transforming values
Each SELECT-list item can be an expression, a function call, a literal or a scalar subquery. This is where INSERT ... SELECT does more than copy.
INSERT INTO emp_stage (emp_id, emp_name, dept_id, salary, status)
SELECT e.emp_id,
UPPER(e.emp_name),
e.dept_id,
ROUND(e.salary * 1.10, 2),
'ACTIVE'
FROM emp_demo e
JOIN dept_demo d ON d.dept_id = e.dept_id
WHERE d.dept_name = 'Engineering';Here the names are uppercased, the salary gets a 10 percent increase rounded to cents, the status is a literal, and the rows are filtered through a join to dept_demo.
Generating keys
When the target has a primary key and the source does not supply one, you must generate it. A sequence works:
CREATE SEQUENCE emp_stage_seq START WITH 1000;
INSERT INTO emp_stage (emp_id, emp_name, dept_id, salary)
SELECT emp_stage_seq.NEXTVAL, emp_name, dept_id, salary
FROM emp_demo;NEXTVAL is evaluated once per returned row. It cannot be used in a SELECT that contains DISTINCT, GROUP BY or ORDER BY at the same query level, so put such logic in an inline view and apply NEXTVAL in the outer query.
The target and source can be the same table
A query can read the table it inserts into. Oracle evaluates the SELECT against a consistent view of the data as of the start of the statement, so the new rows do not feed back into the query and there is no infinite loop.
-- Duplicate every Sales employee under a new key
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary, status)
SELECT emp_id + 100, emp_name, dept_id, salary, status
FROM emp_demo
WHERE dept_id = 10;This is useful for cloning rows. The new key values must not collide with existing keys, or the statement fails with ORA-00001.
All or nothing
A single INSERT ... SELECT is atomic. If any row fails, for example by violating a constraint, Oracle undoes every row that statement had inserted. The effect is a statement-level rollback. Earlier work in your transaction stays in place.
-- Suppose one row in emp_stage has a dept_id that does not exist in dept_demo.
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary, status)
SELECT emp_id, emp_name, dept_id, salary, status
FROM emp_stage;
-- ORA-02291: integrity constraint (...) violated - parent key not found
-- Zero rows from this statement are inserted.For a large load, one bad row among a million discards all of them. The chapter on LOG ERRORS shows how to log bad rows and keep the rest. The chapter on constraint errors explains ORA-00001, ORA-02291 and ORA-02292 in detail.
Statement flow
The diagram shows what happens inside the statement.
Checking what you copied
After the insert, compare counts before you commit. SQL*Plus and SQLcl print the row count, and in PL/SQL SQL%ROWCOUNT gives the same number.
DECLARE
v_expected NUMBER;
BEGIN
SELECT COUNT(*) INTO v_expected
FROM emp_demo
WHERE status = 'INACTIVE';
INSERT INTO emp_archive (emp_id, emp_name, dept_id, salary, status)
SELECT emp_id, emp_name, dept_id, salary, status
FROM emp_demo
WHERE status = 'INACTIVE';
IF SQL%ROWCOUNT = v_expected THEN
COMMIT;
ELSE
ROLLBACK;
END IF;
END;
/The count query and the insert run at slightly different moments, so a concurrent session could change the data between them. For strict checks, run both in a serializable transaction or lock the source rows first.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| No column list, tables differ | ORA-00913 or ORA-00947, or misplaced values after a schema change | Always name the target columns |
| SELECT list in the wrong order | No error, wrong data | Compare the two lists side by side |
| Missing WHERE clause | Entire source table copied | Run the SELECT alone first and check its count |
| Running the statement twice | ORA-00001 on the second run, or duplicate rows if no unique key exists | Use a NOT EXISTS filter or MERGE |
| Skipping a NOT NULL column with no default | ORA-01400 | Supply the column or add a default |
| Value too large for target column | ORA-12899 | Widen the column or trim the value with SUBSTR |
Making a copy safe to repeat
To avoid duplicates when a script reruns, filter out rows that already exist in the target:
INSERT INTO emp_archive (emp_id, emp_name, dept_id, salary, status)
SELECT e.emp_id, e.emp_name, e.dept_id, e.salary, e.status
FROM emp_demo e
WHERE e.status = 'INACTIVE'
AND NOT EXISTS (SELECT 1
FROM emp_archive a
WHERE a.emp_id = e.emp_id);Running this twice inserts the row once. If you also need to update rows that already exist, MERGE is the better tool, and a later chapter covers it.
Performance notes
- INSERT ... SELECT is much faster than a PL/SQL loop that inserts one row at a time, because it runs as one SQL statement with no context switches between PL/SQL and SQL.
- It generates undo and redo for every row. A very large copy can strain undo space, so some teams load in chunks and commit between chunks.
- For bulk loads where you do not need other sessions to read the target while you load, the direct-path insert with the APPEND hint can cut redo and speed up the load. A later chapter covers it.
- Indexes on the target are maintained row by row, which costs time. Constraints and triggers on the target also fire for each row.
Summary
INSERT ... SELECTcopies the rows from any query into a table in one atomic statement.- Columns match by position, so list them explicitly and check the order.
- The SELECT can join, filter and compute, and it can read the target table itself.
- One failing row rolls back the whole statement. Use LOG ERRORS to continue past bad rows.
- Nothing is permanent until COMMIT.
Exercise
You run INSERT INTO emp_archive (emp_id, emp_name, dept_id, salary, status) SELECT emp_id, emp_name, salary, dept_id, status FROM emp_demo; and it succeeds with no error. Name the problem, and write a corrected statement that copies only active employees.
Show answer
Oracle matches columns by position, so salary was inserted into dept_id and dept_id into salary. Both are NUMBER, so no type error was raised, and the data is wrong (a foreign key on deptid may also fail or not, depending on the values). The corrected statement is: INSERT INTO emparchive (empid, empname, deptid, salary, status) SELECT empid, empname, deptid, salary, status FROM emp_demo WHERE status = 'ACTIVE';
Exercise
A nightly script runs INSERT ... SELECT to copy inactive employees from empdemo into emparchive. On the second night it fails with ORA-00001. Why, and how can you change the statement so it can be rerun safely?
Show answer
The second run tries to insert rows whose empid values already exist in emparchive, which violates the primary key. Add a filter such as AND NOT EXISTS (SELECT 1 FROM emparchive a WHERE a.empid = e.empid), with empdemo aliased as e, so only rows not yet archived are copied. MERGE is an alternative if existing rows should also be updated.