Tuesday, May 12, 2009

Oracle SQL: ROWID Pseudocolumn

Again, one of my students asked me a question during the Oracle 11g Introduction to SQL class.

"How would you delete only 1 record of 2 identical records, all with same column values and there is no PK (Primary Key) to uniquely identify them?"

I told her that we can make use of the ROWID pseudocolumn.The ROWID pseudocolumn returns the physical address of the row. Oracle Database rowid values contain information necessary to locate a row:
  • The data object number of the object
  • The data block in the datafile in which the row resides
  • The position of the row in the data block (first row is 0)
  • The datafile in which the row resides (first file is 1). The file number is relative to the tablespace.

Usually, a rowid value uniquely identifies a row in the database. However, rows in different tables that are stored together in the same cluster can have the same rowid. Values of the ROWID pseudocolumn have the datatype ROWID or UROWID.

Rowid values have several important uses:

  • They are the fastest way to access a single row.
  • They can show you how the rows in a table are stored.
  • They are unique identifiers for rows in a table.

You should not use ROWID as the primary key of a table. If you delete and reinsert a row with the Import and Export utilities, for example, then its rowid may change. If you delete a row, then Oracle may reassign its rowid to a new row inserted later.

Although you can use the ROWID pseudocolumn in the SELECT and WHERE clause of a query, these pseudocolumn values are not actually stored in the database. You cannot insert, update, or delete a value of the ROWID pseudocolumn.

The ROWID Demo

To simulate the scenario, I created a sample table named Test:
SQL> CREATE TABLE Test
(test varchar2(10));
Then, I inserted two identical records with no primary key
SQL> INSERT INTO Test
VALUES ('Test1');
SQL> INSERT INTO Test
VALUES ('Test1');
Then, selected the rowid of two identical records
SQL> SELECT rowid, test
FROM Test;
Then, the query returned

ROWID TEST
-------------------- ---------------
AAASDcAAEEAADOMAAA Test1
AAASDcAAEEAADOMAAB Test1
Then, I tried to delete one of the two identical records
SQL> DELETE FROM Test
WHERE rowid = 'AAASDcAAEEAADOMAAA';
Then, the result says 1 row deleted

Yey, we've successfully deleted one of the two identical records. ^_~

No comments: