Sub topic 2
Adding rows with INSERT ... VALUES
This chapter covers the single-row form of INSERT in Oracle. It assumes you can write basic SELECT queries with WHERE clauses. It also assumes you know the common data types (NUMBER, VARCHAR2, DATE) and what primary key, foreign key, and NOT NULL constraints do. You should be able to run SQL in SQL*Plus, SQL Developer, or SQLcl.
What INSERT ... VALUES does
INSERT ... VALUES adds exactly one row to a table. You name the table, optionally list the columns, and supply one value for each listed column. The statement is DML (data manipulation language). Like other DML, it changes data inside a transaction, and the change is not permanent until you commit.
The general form is:
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);Later chapters cover INSERT ... SELECT, which adds many rows at once. This chapter stays with the VALUES form.
The demo schema
The examples in this tutorial use four small tables, so you do not need a sample schema such as HR. Create them now. emp_stage and emp_archive are empty copies of emp_demo. The WHERE 1 = 0 condition is never true, so no rows are copied, only the column definitions.
CREATE TABLE dept_demo (
dept_id NUMBER PRIMARY KEY,
dept_name VARCHAR2(50) NOT NULL
);
CREATE TABLE emp_demo (
emp_id NUMBER PRIMARY KEY,
emp_name VARCHAR2(50) NOT NULL,
dept_id NUMBER REFERENCES dept_demo (dept_id),
salary NUMBER(8,2),
status VARCHAR2(10) DEFAULT 'ACTIVE' NOT NULL
);
CREATE TABLE emp_stage AS SELECT * FROM emp_demo WHERE 1 = 0;
CREATE TABLE emp_archive AS SELECT * FROM emp_demo WHERE 1 = 0;Note what emp_demo enforces:
emp_idis the primary key, so it must be unique and not null.emp_nameandstatusareNOT NULL.dept_idis a foreign key todept_demo. It may be null, but if it has a value, that value must exist indept_demo.statushas aDEFAULTof'ACTIVE'.
Tables created with CREATE TABLE ... AS SELECT copy the column names, data types, and NOT NULL constraints. They do not copy primary keys, foreign keys, or defaults. This matters later when you use emp_stage for loads.
Inserting rows with an explicit column list
Here is the first set of inserts. Parent rows go in first, because the foreign key on emp_demo.dept_id requires the department to exist.
INSERT INTO dept_demo (dept_id, dept_name) VALUES (10, 'Sales');
INSERT INTO dept_demo (dept_id, dept_name) VALUES (20, 'Engineering');
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary)
VALUES (1, 'Ada', 20, 9000);
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary, status)
VALUES (2, 'Grace', 10, 7000, 'INACTIVE');
COMMIT;Values match columns by position. The first value goes into the first listed column, the second into the second, and so on. The number of values must equal the number of columns, and each value must be compatible with its column's data type.
The first employee statement leaves out status. Oracle uses the column's DEFAULT, so Ada gets 'ACTIVE'. The second statement lists status and supplies 'INACTIVE', so Grace gets that value.
The final COMMIT makes all four inserts permanent and visible to other sessions. Until then, only your session sees them. Before committing, you can undo them with ROLLBACK.
Why you should always list the columns
Oracle allows you to omit the column list:
INSERT INTO dept_demo VALUES (30, 'Support');In this form, Oracle expects one value for every column, in the order the table defines them. It works, but it is fragile. If someone later adds a column to the table, or the column order differs between environments, the statement fails or puts values in the wrong columns. An explicit column list also documents what the statement does.
Use the column list in application code, scripts, and anything stored in version control.
Defaults and NULLs
There are three ways a column can end up without a value you typed. They behave differently.
| Situation | Example | Result |
|---|---|---|
| Column left out of the column list | `INSERT INTO emp_demo (emp_id, emp_name) ...` | Column gets its `DEFAULT`, or NULL if it has none |
| Column listed with the keyword `DEFAULT` | `VALUES (3, 'Linus', 20, 8000, DEFAULT)` | Column gets its `DEFAULT`, or NULL if it has none |
| Column listed with an explicit `NULL` | `VALUES (3, 'Linus', 20, NULL, 'ACTIVE')` | Column gets NULL, and the default is ignored |
The last row is a common trap. If you insert an explicit NULL into status, Oracle does not substitute the default. It tries to store NULL, and the NOT NULL constraint rejects the row with ORA-01400.
Here is the DEFAULT keyword in use:
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary, status)
VALUES (3, 'Linus', 20, 8000, DEFAULT);This is useful when a program builds a statement with a fixed set of columns and wants the database to choose the value for some of them.
A NUMBER column such as salary has no default and no NOT NULL, so leaving it out stores NULL. NULL means "unknown or not applicable". It is not zero.
Writing values: literals, expressions, and functions
The VALUES list accepts more than plain literals. You can use any expression that produces a single value.
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary)
VALUES (4, UPPER('margaret'), 10, 5000 * 1.1);Here UPPER('margaret') stores MARGARET, and 5000 * 1.1 stores 5500. You can also call functions such as SYSDATE or SYSTIMESTAMP for date columns. The demo tables have no date column, but the syntax is the same.
Some points about literals:
- Text literals use single quotes. To include a single quote inside the text, double it:
'O''Brien'. - Number literals have no quotes. Oracle will convert
'7000'to a number for you, but relying on that implicit conversion hides mistakes. Write numbers as numbers. - For dates, avoid strings that depend on session settings. Use a date literal such as
DATE '2026-11-28'orTO_DATE('2026-11-28', 'YYYY-MM-DD'). - A subquery in
VALUESis allowed if it returns exactly one value, for example(SELECT dept_id FROM dept_demo WHERE dept_name = 'Sales'). It fails if it returns more than one row. If it returns no rows, the value is NULL.
You cannot insert several rows with one VALUES list that contains multiple tuples in the older Oracle releases. Statements like VALUES (1, 'a'), (2, 'b') raise an error in releases before Oracle Database 23ai. If you need several rows from one statement, use INSERT ALL, INSERT ... SELECT, or a PL/SQL loop. Check your release before relying on multi-row VALUES.
Transaction behavior
An INSERT starts a transaction if one is not already open. Until you end it, the new row is visible only to your session. The ending options are:
COMMITmakes every change since the transaction began permanent.ROLLBACKdiscards every change since the transaction began.ROLLBACK TO SAVEPOINT namediscards only the changes made after that savepoint.
DDL statements such as CREATE TABLE commit implicitly, so you do not need to commit the table creation. Inserts are different. They stay uncommitted until you commit.
The last branch is worth remembering. If a single INSERT fails, for example with a constraint violation, Oracle undoes only that statement. Earlier uncommitted work in the same transaction stays in place, and you can still commit or roll back.
Common errors from INSERT
Most failures of INSERT ... VALUES come from constraints and from mismatched lists. Later chapters treat constraint errors in depth. These are the ones you will meet first.
| Error | Meaning | Typical cause |
|---|---|---|
| ORA-00001 | Unique constraint violated | Inserting an `emp_id` that already exists |
| ORA-01400 | Cannot insert NULL | A `NOT NULL` column got NULL, or was left out and has no default |
| ORA-02291 | Integrity constraint violated, parent key not found | `dept_id` has no matching row in `dept_demo` |
| ORA-00913 | Too many values | More values than columns |
| ORA-00947 | Not enough values | Fewer values than columns |
| ORA-12899 | Value too large for column | Text longer than the `VARCHAR2` length |
| ORA-01438 | Value larger than precision | A number with too many digits for `NUMBER(8,2)` |
Try two of them on the demo data:
-- ORA-00001: emp_id 1 already exists
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary)
VALUES (1, 'Duplicate Ada', 20, 9000);
-- ORA-02291: department 99 does not exist
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary)
VALUES (5, 'Orphan', 99, 6000);Each statement fails on its own, and nothing is inserted. The error message names the constraint, such as SYS_C0012345. Query USER_CONSTRAINTS to find which constraint that is. If you give constraints explicit names when you create them, the messages become easier to read.
Primary keys and generated values
The demo inserts type each emp_id by hand. In real systems, keys usually come from a generator. Oracle offers sequences, and from Oracle Database 12c onward, identity columns:
CREATE TABLE note_demo (
note_id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
body VARCHAR2(200) NOT NULL
);
INSERT INTO note_demo (body) VALUES ('First note');With GENERATED ALWAYS, you must leave note_id out of the column list. Supplying a value raises ORA-32795. With a sequence, you call my_seq.NEXTVAL inside the VALUES list instead.
Generated keys are not gap-free. A rolled-back insert still consumes a number.
Practical habits
- Insert parent rows before child rows, so foreign keys are satisfied.
- Use bind variables in application code instead of building statements by concatenating text. Bind variables avoid SQL injection and let Oracle reuse the parsed statement.
- Commit when a unit of work is complete, not after every row and not never. Committing too often is slow and breaks atomicity. Not committing holds your changes in limbo and can block other sessions.
- Check the "1 row inserted" feedback in your tool. A script that ignores errors can leave half the data behind.
Exercise
You run INSERT INTO empdemo (empid, empname, deptid, salary, status) VALUES (6, 'Edsger', 20, 8500, NULL); and get ORA-01400, even though status has DEFAULT 'ACTIVE'. Why did the default not apply, and how would you change the statement so that Edsger gets status 'ACTIVE'?
Show answer
An explicit NULL in the VALUES list is stored as NULL. The default only applies when the column is omitted from the column list or given the DEFAULT keyword. Because status is NOT NULL, the NULL is rejected. Either remove status from the column list, or write DEFAULT in place of NULL in the VALUES list.
Exercise
A script inserts a row into empdemo with deptid 30, but dept_demo contains only departments 10 and 20. Which error does Oracle raise, and what is the smallest fix that keeps the foreign key in place?
Show answer
Oracle raises ORA-02291 (integrity constraint violated, parent key not found). Insert the parent row first, for example INSERT INTO deptdemo (deptid, dept_name) VALUES (30, 'Support');, and then insert the employee row.
Exercise
You insert three rows without committing, and the third statement fails with ORA-00001. What state is the transaction in, and what do you do next?
Show answer
Only the failed third statement is undone. The first two inserts are still part of your open transaction. You can fix the third row and run it again, then COMMIT, or you can ROLLBACK to discard all of the work.