Changing Data with DML
How to add, change, and remove rows safely with INSERT, UPDATE, DELETE, and MERGE, and what the errors mean when the database says no.
Four ways to change data
Querying reads data; the statements in this lesson change it. They're the core of every application, and the ones that need the most care, because a mistake changes real data.
The examples use the sample tables. After each statement, SQL*Plus reports how many rows it changed, such as 1 row updated. Always read that number: it's your first sign that something went wrong.
INSERT: adding rows
INSERT adds a new row. List the columns, then the values in the same order:
INSERT INTO sales.customers (customer_id, name, city)
VALUES (6, 'Abena', 'Ho');
1 row created.
The joined_on column was left out, so it gets its default value: today's date, as defined when the table was created. A column with no default is left empty (NULL).
New orders work the same way. Here, order_date defaults to today and status to 'PENDING':
INSERT INTO sales.orders (order_id, customer_id, amount)
VALUES (107, 6, 180);
1 row created.
Copying rows from a query
INSERT … SELECT inserts the result of a query, which is how you copy many rows at once. Here, cancelled orders are copied into an archive table with the same columns:
INSERT INTO sales.orders_archive
SELECT * FROM sales.orders WHERE status = 'CANCELLED';
1 row created.
When an insert is rejected
The table's constraints, its built-in rules, reject bad data. These are the errors you'll meet most:
| Mistake | Error |
|---|---|
| Reusing an ID that already exists | ORA-00001: unique constraint (SALES.CUSTOMERS_PK) violated |
| Leaving a required column empty | ORA-01400: cannot insert NULL into ("SALES"."CUSTOMERS"."NAME") |
| An order for a customer that doesn't exist | ORA-02291: integrity constraint (SALES.ORDERS_CUSTOMER_FK) violated - parent key not found |
| A value that breaks a rule, such as a negative amount | ORA-02290: check constraint (SALES.ORDERS_AMOUNT_CK) violated |
The name in parentheses tells you which rule was broken. The Constraints and Indexes lesson explains each of these rules.
UPDATE: changing rows
UPDATE changes values in rows that already exist. SET says what to change, and WHERE says which rows:
UPDATE sales.orders
SET status = 'SHIPPED'
WHERE order_id = 105;
1 row updated.
Change several columns at once by separating them with commas:
UPDATE sales.customers
SET name = 'Esi Mensah',
city = 'Cape Coast'
WHERE customer_id = 4;
1 row updated.
A new value can be calculated from the current one. This gives all of Kofi's orders a 10% discount:
UPDATE sales.orders
SET amount = amount * 0.9
WHERE customer_id = 1;
3 rows updated.
-- 1. Check which rows will change
SELECT order_id, status FROM sales.orders WHERE order_id = 105;
-- 2. Change them, using the same WHERE
UPDATE sales.orders SET status = 'SHIPPED' WHERE order_id = 105;
-- 3. Did the row count match? If yes, COMMIT. If not, ROLLBACK.
DELETE: removing rows
DELETE removes the rows that match its WHERE clause:
DELETE FROM sales.orders
WHERE status = 'CANCELLED';
1 row deleted.
Foreign keys protect related data. You can't delete a customer who still has orders, because those orders would point to a customer that no longer exists:
DELETE FROM sales.customers WHERE customer_id = 1;
ORA-02292: integrity constraint (SALES.ORDERS_CUSTOMER_FK) violated - child record found
Delete or move the customer's orders first, then the customer.
MERGE: update or insert
Sometimes you have new data and don't know whether each row already exists: update it if it does, insert it if it doesn't. This is called an upsert, and MERGE does it in one statement:
MERGE INTO sales.customers c
USING (SELECT 6 AS customer_id, 'Abena' AS name, 'Cape Coast' AS city FROM dual) s
ON (c.customer_id = s.customer_id)
WHEN MATCHED THEN
UPDATE SET c.city = s.city
WHEN NOT MATCHED THEN
INSERT (customer_id, name, city) VALUES (s.customer_id, s.name, s.city);
1 row merged.
Read it in four parts:
MERGE INTO: the table to change,sales.customers.USING: the new data. Here it's a single row built fromDUAL; in practice it's usually another table, such as a daily import.ON: how to tell whether a row already exists, by matchingcustomer_id.WHEN MATCHEDandWHEN NOT MATCHED: what to do in each case. Abena (customer 6) already exists, so the city is updated.
Key takeaways
INSERTadds rows,UPDATEchanges them,DELETEremoves them, andMERGEupdates or inserts in one step.- Always list the columns in an
INSERT. Columns you leave out get their default value, or NULL. - An
UPDATEorDELETEwithoutWHEREchanges every row. Test theWHEREwith aSELECTfirst, and check the row count. - Constraints reject bad data, and the error names the rule that was broken.
- Nothing is permanent until
COMMIT.