SQL Question #1
How can 2 views be used to delete data in
one of the views? V1 has two fields, K1 and
K2. V2 has field K2 and I need to delete
all rows in V2 based on K1 in V1 so the
views can be joined v1.k2 = v2.k2 but how
would the delete statement be written?
1. delete from V2 2. delete from V2
where K1 in (select V2.K1 where rowid in (select V2.rowid
from V2, V1 from V2, V1
where V2.K2 = where V2.K2 =
3. delete from V2 4. delete from V2, V1
where K2 in (select V2.K2 where V1.K2 = V2.K2;
from V2, V1
where V2.K2 =
Both 2 and 3.
2 is better because using rowid would make
What is Rowid?
A rowid is a pseudo column (like versions_xid),
that uniquely identifies a row within a table, but not
within a database.
Every record has a unique ROWID within a
database representing the physical location on
disk where the record lives. Every record has a
unique ROWID within a database representing the
physical location on disk where the record lives.
The ROWID gives us the physical address of a
row and is the fastest way to access any row.
Common Case for Rowid
Table V2 has a column "K1", which should
be unique, but someone made a mistake
and did not add a primary key or unique
constraint, and there are now duplicate
rows. We want to clean it up.
delete from V2 a where exists (
select 1 from V2 b where a.K1 = b.K1
and b.ROWID < a.ROWID);
The self-join query means "Delete all rows that
have another row with the same K1, but "lesser"
ROWID. Our choice of "lesser", while not logically
required, so we prefer to preserve the row that is
closer to the beginning of the table. The main point
is without the ROWID, the only way to correct this
table would be to create a new one based on the
results of a query with GROUP BY K1, or to use
other columns and methods to differentiate. While
feasible, it might not be convenient for various
reasons, so it is good to know the ROWID is