Sub topic 12
Matching a Whole Row with %ROWTYPE
This chapter assumes you can write and run an anonymous block, declare variables, use SELECT INTO, and anchor a single variable with %TYPE. You also need access to a schema with the HR.EMPLOYEES table.
What %ROWTYPE does
%TYPE anchors one variable to one column. %ROWTYPE anchors a whole record to a whole row. A record is a composite variable that holds several named fields. When you write employees%ROWTYPE, PL/SQL creates a record with one field per column of EMPLOYEES. Each field has the same name, data type, and size as its column.
SET SERVEROUTPUT ON
DECLARE
v_emp employees%ROWTYPE;
BEGIN
SELECT *
INTO v_emp
FROM employees
WHERE employee_id = 100;
DBMS_OUTPUT.PUT_LINE(v_emp.first_name || ' ' || v_emp.last_name);
END;
/You read a field with dot notation: record_name.column_name. Here v_emp.first_name is a VARCHAR2 that matches EMPLOYEES.FIRST_NAME.
The %ROWTYPE attribute is resolved when the block is compiled. If a DBA adds a column to EMPLOYEES later, your record gains that field after the next compilation. A named block, such as a stored procedure, is recompiled automatically when it is next used after the table changes. An anonymous block is compiled every time you run it, so it always sees the current structure.
What you can anchor to
The prefix before %ROWTYPE does not have to be a table. It can be any of the following:
| Prefix | Example | Fields come from |
|---|---|---|
| Table | `employees%ROWTYPE` | Every column of the table |
| View | `emp_details_view%ROWTYPE` | Every column of the view |
| Explicit cursor | `c_emp%ROWTYPE` | The select list of the cursor query |
| Cursor variable | `rc%ROWTYPE` | The select list of a strongly typed cursor |
Cursors are covered in a later chapter. For now, remember that the same attribute works on a query's select list as well as on a table.
Filling a record with SELECT INTO
The most common way to fill a record is SELECT * INTO record. With a single record on the right of INTO, PL/SQL matches columns to fields by position. The query must return the same number of columns as the record has fields, in the same order, with compatible types.
SELECT * works with a table record because the column order of the table and the record are the same. If you select fewer columns than the record has, you get a compile error, so a partial query needs a different declaration.
SET SERVEROUTPUT ON
DECLARE
v_emp employees%ROWTYPE;
BEGIN
SELECT *
INTO v_emp
FROM employees
WHERE employee_id = 101;
DBMS_OUTPUT.PUT_LINE('Name: ' || v_emp.first_name || ' ' || v_emp.last_name);
DBMS_OUTPUT.PUT_LINE('Job: ' || v_emp.job_id);
DBMS_OUTPUT.PUT_LINE('Salary: ' || v_emp.salary);
DBMS_OUTPUT.PUT_LINE('Hired: ' || TO_CHAR(v_emp.hire_date, 'YYYY-MM-DD'));
END;
/Because SELECT INTO expects exactly one row, a record does not change the error behavior from the previous chapters. Zero rows raise NO_DATA_FOUND. More than one row raises TOO_MANY_ROWS.
Assigning fields and whole records
A field of a record is an ordinary variable. You can read it, assign to it, and pass it to functions.
SET SERVEROUTPUT ON
DECLARE
v_emp employees%ROWTYPE;
BEGIN
SELECT * INTO v_emp
FROM employees
WHERE employee_id = 100;
v_emp.salary := v_emp.salary * 1.05;
v_emp.commission_pct := NVL(v_emp.commission_pct, 0);
DBMS_OUTPUT.PUT_LINE(v_emp.last_name || ' new salary: ' || v_emp.salary);
END;
/The change affects only the record in memory. The table is unchanged until you run an UPDATE statement.
You can also copy one record into another when both are declared with the same %ROWTYPE. The assignment copies every field.
SET SERVEROUTPUT ON
DECLARE
v_current employees%ROWTYPE;
v_original employees%ROWTYPE;
BEGIN
SELECT * INTO v_current
FROM employees
WHERE employee_id = 100;
v_original := v_current;
v_current.salary := v_current.salary + 1000;
DBMS_OUTPUT.PUT_LINE('Original: ' || v_original.salary);
DBMS_OUTPUT.PUT_LINE('Current: ' || v_current.salary);
END;
/The two records are independent copies. Changing v_current.salary does not change v_original.salary.
Records have no comparison operators. You cannot write IF v_current = v_original. To compare, test the fields you care about one at a time.
Using a record in DML
Records are not only for reading. In INSERT and UPDATE statements you can supply a whole record, which saves you from listing every column.
SET SERVEROUTPUT ON
DECLARE
v_emp employees%ROWTYPE;
BEGIN
SELECT * INTO v_emp
FROM employees
WHERE employee_id = 100;
v_emp.employee_id := 9999;
v_emp.email := 'TEMP9999';
INSERT INTO employees VALUES v_emp;
DBMS_OUTPUT.PUT_LINE('Rows inserted: ' || SQL%ROWCOUNT);
ROLLBACK;
END;
/Two rules apply. The record must be the only item after VALUES, with no parentheses. And the insert uses every column in table order, so the record must be fully populated.
The ROLLBACK at the end undoes the test row. Without it, this block would leave a copy of the first employee in your table. It would also fail if the table has other unique constraints that the copy violates, such as a unique EMAIL, which is why the example changes email.
For updates, use SET ROW:
DECLARE
v_emp employees%ROWTYPE;
BEGIN
SELECT * INTO v_emp
FROM employees
WHERE employee_id = 100;
v_emp.salary := v_emp.salary + 500;
UPDATE employees
SET ROW = v_emp
WHERE employee_id = v_emp.employee_id;
ROLLBACK;
END;
/SET ROW overwrites every column, including the primary key and columns that other sessions may have changed since you read the row. Use it when you really mean to replace the whole row. For a targeted change, name the columns in a normal SET clause.
Partial records and select lists
A table-based %ROWTYPE always has all columns. If you only need a few, there are two choices.
The first is to declare individual %TYPE variables, as in the earlier chapter. The second is to anchor the record to a cursor whose query selects only those columns:
SET SERVEROUTPUT ON
DECLARE
CURSOR c_pay IS
SELECT last_name, salary
FROM employees
WHERE employee_id = 100;
v_pay c_pay%ROWTYPE;
BEGIN
OPEN c_pay;
FETCH c_pay INTO v_pay;
CLOSE c_pay;
DBMS_OUTPUT.PUT_LINE(v_pay.last_name || ': ' || v_pay.salary);
END;
/The record v_pay has exactly two fields, last_name and salary. Computed columns in the select list need an alias, because the alias becomes the field name. Without an alias, the compiler cannot name the field.
Choosing between %ROWTYPE and %TYPE
The choice depends on how many columns you need and how the code should respond to schema changes.
| Situation | Better choice |
|---|---|
| Need most or all columns of a row | `%ROWTYPE` |
| Need one or two columns | `%TYPE` variables |
| Passing a row to a procedure | `%ROWTYPE` parameter |
| Inserting or updating whole rows | `%ROWTYPE` record |
| Reading a large table where only a few columns matter | `%TYPE` or a cursor-based record |
Fetching every column when you use two of them wastes work. This matters most for tables with wide columns such as CLOB, because the database reads and moves data you never look at.
Gotchas
- NULLs. A field inherits nothing about
NOT NULLfrom its column. A%ROWTYPEfield can hold NULL even if the column isNOT NULL. TheNOT NULLconstraint on a column is not copied. Only the data type and size are. The database still enforces the constraint when you runINSERTorUPDATE. - Default values. Column defaults are not copied either. A freshly declared record has every field set to NULL, so a record you insert without setting a field inserts NULL, not the column default.
- Uninitialized records. You cannot give a
%ROWTYPErecord an initial value in the declaration section with:=unless you assign another record of the same type. Fill it in the executable section. - Dot notation on a missing field. If you misspell a field name, the block fails to compile with
PLS-00302: component must be declared. This is helpful. It catches typos before the code runs. - Column order with SELECT INTO. When you list columns instead of using
*, the list must match the record's field count and order. PreferSELECT *for table-anchored records. - Schema changes. If a column is dropped and your code uses it, the named block becomes invalid on its next compile. You find out at compile time, not when a user runs it.
How the pieces connect
The diagram shows how a record moves through a block: it is declared from the table's structure, filled by a query, changed in memory, and written back with DML.
Handling errors
A record-based SELECT INTO fails the same way as a variable-based one. Put an exception section around it.
SET SERVEROUTPUT ON
DECLARE
v_emp employees%ROWTYPE;
BEGIN
SELECT * INTO v_emp
FROM employees
WHERE employee_id = -1;
DBMS_OUTPUT.PUT_LINE(v_emp.last_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee with that ID.');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('More than one row matched.');
END;
/After NO_DATA_FOUND, the contents of the record are not reliable, so do not use its fields in the handler.
Summary
table%ROWTYPEdeclares a record with one field per column, with the same names and data types.- Fields are read and assigned with
record.field. SELECT * INTO recordfills the whole record by position.- Records of the same type can be assigned to each other, but not compared with
=. INSERT ... VALUES recordandUPDATE ... SET ROW = recordwork with whole records.- Constraints and defaults are not copied from the table.
Exercise
A block declares v_emp employees%ROWTYPE and runs SELECT employee_id, last_name INTO v_emp FROM employees WHERE employee_id = 100;. What happens, and how would you fix it?
Show answer
The block fails to compile, because the record has one field per column of EMPLOYEES but the query returns only two columns. Fix it either by using SELECT * INTO v_emp, or by declaring two %TYPE variables (employees.employee_id%TYPE and employees.last_name%TYPE) and selecting into those. A third option is a cursor with that select list and a variable declared as cursor_name%ROWTYPE.
Exercise
The column EMPLOYEES.HIRE_DATE is NOT NULL. A block declares v_emp employees%ROWTYPE and, without setting v_emp.hire_date, runs INSERT INTO employees VALUES v_emp;. Why does the insert fail, even though the block compiled?
Show answer
%ROWTYPE copies the data type and size of each column but not its NOT NULL constraint or default. So the record is legal and compiles, and v_emp.hire_date is NULL. The database enforces the constraint when the INSERT runs and raises ORA-01400 (cannot insert NULL).