There was a discussion on the OTN General database forum, in which the OP asked creating a table with just one row and restricting that table to just one row. Here is my attempt at it.
I created a table with two columns, and the second column is a virtual column and contains a constant. I created a unique index on this column. On every insertion, this second column always evaluates to 1, and unique index (which become the function based index on virtual column) ensures that only one row remains in the table.
[email protected] # sqlplus /nolog SQL*Plus: Release 11.1.0.7.0
- Production on Sat Aug 28 19:09:16 2010 Copyright (c) 1982, 2008, Oracle. All rights reserved. idle> conn test/test Connected. [email protected]> create table t1
(c1 number, c2 generated always as (1) virtual); Table created. [email protected]> create unique index idx1 on t1(c2); Index created. [email protected]> insert into t1(c1) values (1); 1 row created. [email protected]> commit; Commit complete. [email protected]> insert into t1(c1) values (1); insert into t1(c1) values (1) * ERROR at line 1: ORA-00001: unique constraint (TEST.IDX1) violated [email protected]> insert into t1(c1) values (2); insert into t1(c1) values (2) * ERROR at line 1: ORA-00001: unique constraint (TEST.IDX1) violated
3 Comments. Leave new
Hi,
simple unique index on any constant instead of column is simpler I think, and works on older versions too..
Here’s a sample
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 – 64bit Production
With the Partitioning, Real Application Clusters, OLAP, Data Mining
and Real Application Testing options
SQL> create table t1 (c1 number);
Table created.
SQL> create unique index idx1 on t1(1);
Index created.
SQL> insert into t1(c1) values (1);
1 row created.
SQL> commit;
Commit complete.
SQL> insert into t1(c1) values (2);
insert into t1(c1) values (2)
*
ERROR at line 1:
ORA-00001: unique constraint (TEST.IDX1) violated
Maris
This is brilliant. Pure genius. Thanks!
I have been hitting some bugs while using constant numbers in virtual columns. Check your virtual column data type. Sometimes queries from such column return numbers from 0.9999 to 1.0000. Also seen situations where null returned. I would suggest casting your constant number one to a specific length while creating such table. c2 number(1) as (cast (1 as number(1)))