UNIQUE INDEX and PRIMARY KEYS
Hi Friends,
I am confused about primary keys.
What is the purpose of this key again? I know it is used for unique constraints.
Supposing I have a table with two (2) columns which are each indexed as unique.
Then they can me both candidate at primary key right?
So why do I need a primary key again? when I have 2 columns which are uniquely index?
Thanks a lot
A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index allows multiple NULL values for columns that can contain NULL
The differences between the two are:
1. Column(s) that make the Primary Key of a table cannot be NULL since by definition; the Primary Key cannot be NULL since it helps uniquely identify the record in the table. The column(s) that make up the unique index can be nullable. A note worth mentioning over here is that different RDBMS treat this differently –> while SQL Server and DB2 do not allow more than one NULL value in a unique index column, Oracle allows multiple NULL values. That is one of the things to look out for when designing/developing/porting applications across RDBMS.
2. There can be only one Primary Key defined on the table where as you can have many unique indexes defined on the table (if needed).
3. Also, in the case of SQL Server, if you go with the default options then a Primary Key is created as a clustered index while the unique index (constraint) is created as a non-clustered index. This is just the default behavior though and can be changed at creation time, if needed.
So, if the unique index is defined on not null column(s), then it is essentially the same as the Primary Key and can be treated as an alternate key meaning it can also serve the purpose of identifying a record uniquely in the table.
Similar Messages
-
Difference between Unique key and Primary key(other than normal difference)
Hello,
1).Can any one tell me any other difference between Unique key and Primary key other than it having NULLs.
2). What is the difference the words 'DISTINCT' and 'UNIQUE' in a sql query.
Thanks in advance.Hi
If you don't believe me than see the documentation in
OTN.
Ott Karesz
http://www.trendo-kft.hu
SQL> create table scott.tbl_clob
2 (sss CLOB)
3 /
Tabelle wurde angelegt.
SQL> insert into scott.tbl_clob values('wrwrwrw')
2 /
1 Zeile wurde erstellt.
SQL> insert into scott.tbl_clob values('wrwrwrw')
2 /
1 Zeile wurde erstellt.
SQL> select distinct sss from scott.tbl_clob
2 /
select distinct sss from scott.tbl_clob
FEHLER in Zeile 1:
ORA-00932: nicht übereinstimmende Datentypen
SQL> select unique sss from scott.tbl_clob
2 /
select unique sss from scott.tbl_clob
FEHLER in Zeile 1:
ORA-00932: nicht übereinstimmende Datentypen
SQL> select distinct to_char(sss) from scott.tbl_clob
2 /
TO_CHAR(SSS)
wrwrwrw
SQL> select unique to_char(sss) from scott.tbl_clob
2 /
TO_CHAR(SSS)
wrwrwrw
SQL> -
Recreate indexes,triggers and primary keys.
Hi All,
We have done an import of few table from MS SQL Server to oracle. But we couldnt see the indexes, triggers, primary key, foreign key of those tables.
Could you please let us know how to recreate the primary key, foreign key, indexes, triggers etc of those tables.
Pl suggest.
Thanks in advance!
Regards,
Vidhya>
We have done an import of few table from MS SQL Server to oracle
>
What does that mean exactly? How did you do an import from sql server to Oracle?
Post your 4 digit Oracle version (result of SELECT * FROM V$VERSION) and the exact steps you took to 'import'. -
column with unique constraint + not null constraint = primary key! (to some extent) Is it correct?
I invite your ideashttp://www.techonthenet.com/oracle/unique.php
http://www.allapplabs.com/interview_questions/db_interview_questions.htm#q13
Difference between Unique key and Primary key(other than normal difference) -
Function Based Indexes in Primary Key Definition
Hello.
I have been looking into function based indexes. I have been able to create them using unique indexes. However, when I try to create them on primary keys, the engine complains.
Any ideas? Does anyone know if you can create function based indexes on primary keys?
An example would be great!
Thanks,
BradHi,
You can create a function-based Index by going to the Properties dialog for the Index in the Relational model (not the Physical model). If you select the Index Expression tick box, you can then enter the expression into the Expression text area.
David -
If you have a table with a unique index and ignore_dup_key = on and you INSERT rows into that table with an ORDER BY clause (because you want to control which of the duplicate
key rows gets inserted), the wrong row gets inserted in SQL2012. It works correctly in SQL 2008.
We have recently migrated a database from SQL 2008 to SQL 2012. We do have few other dbs which are in compatability mode 100. The above operation works fine
in SQL 2008 dbs but not SQL 2012.
I've even tried applying the latest patch for SQL 2012 SP2 with CU2. Still the problem exists. I'm going to call MS support, but want to know if anyone has come across this problem ?The MS documentation doesn't guarantee that the first row of the duplicates will always be inserted and the next duplicate row(s) get(s) ignored. Where did you find it in the MS documentation? I think you were just lucky that it was always inserting the
first row in SQL 2008 (and ignoring the rest of the duplicates) - I don't think this is guaranteed
Satish Kartan http://www.sqlfood.com/ -
Dynamic SQL Joining between tables and Primary keys being configured within master tables
Team , Thanks for your help in advance !
I'm looking out to code a dynamic SQL which should refer Master tables for table names and Primary keys and then Join for insertion into target tables .
EG:
INSERT INTO HUB.dbo.lp_order
SELECT *
FROM del.dbo.lp_order t1
where not exists ( select *
from hub.dbo.lp_order tw
where t1.order_id = t2.order_id )
SET @rows = @@ROWCOUNT
PRINT 'Table: lp_order; Inserted Records: '+ Cast(@rows AS VARCHAR)
-- Please note Databse names are going to remain the same but table names and join conditions on keys
-- should vary for each table(s) being configured in master tables
Sample of Master configuration tables with table info and PK Info :
Table Info
Table_info_ID Table_Name
1 lp_order
7 lp__transition_record
Table_PK_Info
Table_PK_Info_ID Table_info_ID PK_Column_Name
2 1 order_id
8 7 transition_record_id
There can be more than one join condition for each table
Thanks you !
Rajkumar YeluguHi Rajkumar,
It is glad to hear that you figured the question out by yourself.
There's a flaw with your while loop in your sample code, just in case you hadn't noticed that, please see below.
--In this case, it goes to infinite loop
DECLARE @T TABLE(ID INT)
INSERT INTO @T VALUES(1),(3),(2)
DECLARE @ID INT
SELECT @ID = MIN(ID) FROM @T
WHILE @ID IS NOT NULL
PRINT @ID
SELECT @ID =ID FROM @T WHERE ID > @ID
So a cursor would be the appropriate option in your case, please reference below.
DECLARE @Table_Info TABLE
Table_info_ID INT,
Table_Name VARCHAR(99)
INSERT INTO @Table_Info VALUES(1,'lp_order'),(7,'lp__transition_record');
DECLARE @Table_PK_Info TABLE
Table_PK_Info_ID INT,
Table_info_ID INT,
PK_Column_Name VARCHAR(99)
INSERT INTO @Table_PK_Info VALUES(2,1,'order_id'),(8,7,'transition_record_id'),(3,1,'order_id2')
DECLARE @SQL NVarchar(MAX),
@ID INT,
@Table_Name VARCHAR(20),
@whereCondition VARCHAR(99)
DECLARE cur_Tabel_Info CURSOR
FOR SELECT Table_info_ID,Table_Name FROM @Table_Info
OPEN cur_Tabel_Info
FETCH NEXT FROM cur_Tabel_Info
INTO @ID, @Table_Name
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @whereCondition =ISNULL(@whereCondition+' AND ','') +'t1.'+PK_Column_Name+'='+'t2.'+PK_Column_Name FROM @Table_PK_Info WHERE Table_info_ID=@ID
SET @SQL = 'INSERT INTO hub.dbo.'+@Table_Name+'
SELECT * FROM del.dbo.'+@Table_Name+' AS T1
WHERE NOT EXISTS (
SELECT *
FROM hub.dbo.'+@Table_Name+' AS T2
WHERE '+@whereCondition+')'
SELECT @SQL
--EXEC(@SQL)
SET @whereCondition = NULL
FETCH NEXT FROM cur_Tabel_Info
INTO @ID, @Table_Name
END
Supposing you had noticed and fixed the flaw, your answer sharing is always welcome.
If you have any question, feel free to let me know.
Eric Zhang
TechNet Community Support -
ORA-01502 error in case of unusable unique index and bulk dml
Hi, all.
The db is 11.2.0.3 on a linux machine.
I made a unique index unusable, and issued a dml on the table.
Howerver, oracle gave me ORA-01502 error.
In order to avoid ORA-01502 error, do I have to drop the unique index ,and do bulk dml, and recreate the index?
Or Is there any other solution without re-creating the unique index?
create table hoho.abcde as
select level col1 from dual connect by level <=1000
10:09:55 HOHO@PD1MGD>create unique index hoho.abcde_dx1 on hoho.abcde (col1);
Index created.
10:10:23 HOHO@PD1MGD>alter index hoho.abcde_dx1 unusable;
Index altered.
Elapsed: 00:00:00.03
10:11:27 HOHO@PD1MGD>delete from hoho.abcde where rownum < 11;
delete from hoho.abcde where rownum < 11
ERROR at line 1:
ORA-01502: index 'HOHO.ABCDE_DX1' or partition of such index is in unusable stateThanks in advance.
Best Regards.Hi. all.
The following is from "http://docs.oracle.com/cd/E14072_01/server.112/e10595/indexes002.htm#CIHJIDJG".
Is there anyone who can show me a tip to avoid the following without dropping and re-creating an unique index?
•DML statements terminate with an error if there are any unusable indexes that are used to enforce the UNIQUE constraint.
Unusable indexes
An unusable index is ignored by the optimizer and is not maintained by DML. One reason to make an index unusable is if you want to improve the performance of bulk loads. (Bulk loads go more quickly if the database does not need to maintain indexes when inserting rows.) Instead of dropping the index and later recreating it, which requires you to recall the exact parameters of the CREATE INDEX statement, you can make the index unusable, and then just rebuild it. You can create an index in the unusable state, or you can mark an existing index or index partition unusable. The database may mark an index unusable under certain circumstances, such as when there is a failure while building the index. When one partition of a partitioned index is marked unusable, the other partitions of the index remain valid.
An unusable index or index partition must be rebuilt, or dropped and re-created, before it can be used. Truncating a table makes an unusable index valid.
Beginning with Oracle Database 11g Release 2, when you make an existing index unusable, its index segment is dropped.
The functionality of unusable indexes depends on the setting of the SKIP_UNUSABLE_INDEXES initialization parameter.
When SKIP_UNUSABLE_INDEXES is TRUE (the default), then:
•DML statements against the table proceed, but unusable indexes are not maintained.
•DML statements terminate with an error if there are any unusable indexes that are used to enforce the UNIQUE constraint.
•For non-partitioned indexes, the optimizer does not consider any unusable indexes when creating an access plan for SELECT statements. The only exception is when an index is explicitly specified with the INDEX() hint.
•For a partitioned index where one or more of the partitions are unusable, the optimizer does not consider the index if it cannot determine at query compilation time if any of the index partitions can be pruned. This is true for both partitioned and non-partitioned tables. The only exception is when an index is explicitly specified with the INDEX() hint.
When SKIP_UNUSABLE_INDEXES is FALSE, then:
•If any unusable indexes or index partitions are present, any DML statements that would cause those indexes or index partitions to be updated are terminated with an error.
•For SELECT statements, if an unusable index or unusable index partition is present but the optimizer does not choose to use it for the access plan, the statement proceeds. However, if the optimizer does choose to use the unusable index or unusable index partition, the statement terminates with an error.Thanks in advance.
Best Regards. -
Table and Primary Key Case Sensitive in Automated Row Fetch
Why are the table and primary key fields case sensitive in the Automated Row Fetch process? I'm debugging an error in this process and I'm not sure what the case should be.
Russ - It's a defect of sorts. Use upper case in the process definition. I don't think these processes will work with tables or columns whose names are not known to the database as upper-case values, i.e., defined using double-quoted non-upper case.
Scott -
CS6: tab index and access key
are the tab index and access key features available in CS6?
Depends on which version you have. I think most Accessibility features were deprecated in 12.2.
Nancy O. -
Logical standby and Primary keys
Hi All,
Why primary keys are essential for creating logical standby database? I have created a logical standby database on testing basis without having primary keys on most of the tables and it's working fine. I have not event put my main DB in force logging mode.I have not event put my main DB in force logging mode. This is because, redo log files or standby redo logfiles transforms into set of sql statements to update logical standby.
Have you done any DML operations with nologging options and do you notice any errors in the alert.log? I just curious to know.
But I wanted to know that, while system tablespace in hot backup mode,In the absence of both a primary key and a nonnull unique constraint/index, all columns of bounded size are logged as part of the UPDATE statement to identify the modified row. In other words, all columns except those with the following types are logged: LONG, LOB, LONG RAW, object type, and collections.
Jaffar -
Performance: index vs. primary key
For reasons beyond my control, I have an Oracle database with no primary keys. Fields that would likely be primary keys, however, are indexed.
Is there any reason to believe that database performance will improve if I do add primary keys?
If yes, why?
Thank you!
-BrentPrimary keys provide unique values and an in built index on thecolumn. Since the fields are indexed converting them to primary keys shall not affect the performance.Yes, if u want unique values they can be defined as Primary Keys.
However if these fields are VARCHAR2 with large size then an index will not improve the performance. You can look at creating new PK as numeric fields with a Sequence.
<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Brent Christensen ([email protected]):
For reasons beyond my control, I have an Oracle database with no primary keys. Fields that would likely be primary keys, however, are indexed.
Is there any reason to believe that database performance will improve if I do add primary keys?
If yes, why?
Thank you!
-Brent<HR></BLOCKQUOTE>
null -
Problem with foreign and primary keys migration from SQL Server to Oracle
Hi folks, i'm using SQL Developer to migrate from a SQL Server database to Oracle and i'm stuck with a couple issues:
The worst of them so far is the fact that i can't migrate any of the PKs and FKs. After successfully capturing the SQL Server DB model and converting it to Oracle, when the tool generates the scripts, all ALTER TABLE queries that add the PKs and FKs have their target columns duplicated.
for example: when i'm trying to migrate a simple table that contains an Id (PK) and Name columns, the tool generates the following scripts:
PROMPT Creating Table TestTable...
CREATE TABLE TestTable (
Id NUMBER(10,0) NOT NULL,
Name VARCHAR2 NOT NULL
PROMPT Creating Primary Key Constraint PK_TestTable on table TestTable ...
ALTER TABLE TestTable
ADD CONSTRAINT PK_TestTable PRIMARY KEY
Id,
Id
ENABLE
As for the FKs, the tool duplicates the columns as well:
ALTER TABLE SomeTable
ADD CONSTRAINT FK_SomeTable_SomeTable2 FOREIGN KEY
SomeTable2Id,
SomeTable2Id
REFERENCES SomeTable2
Id,
Id
ENABLE
Does anyone have a clue on how to solve these issues? I'd be greatly thankful for any answers!Hi Fernando,
I was unable to replicate this issue. My primary / foreign keys where defined using unique columns.
PROMPT Creating Primary Key Constraint PK_Suppliers on table Suppliers ...
ALTER TABLE Suppliers
ADD CONSTRAINT PK_Suppliers PRIMARY KEY
SupplierID
ENABLE
I tried a few things like
capturing twice and renaming both models the same
renaming the converted models
but with no luck.
I think this issue is occuring either at the capture or convert phase.
1) Are you performing the capture online or offline?
2) Can you provide a the entire DDL for one of these tables and its indexes to see if I can replicate?
3) Did the capture or convert fail or have to be redone at any stage ?
I all else fails I would attempt a capture and convert again using a brand new repository (create a new schema in Oracle and associate the migration repository with it).
Regards,
Dermot
SQL Developer Team
Edited by: Dermot ONeill on Oct 22, 2009 12:18 PM -
hi,
I am reading chapter 10 of expert oracle database architecture by tom kyte, and I am getting a little confused. It seems to me as if he is saying that an IOT should be built using the PK of that table. What if our table does not have a PK?
thanksOracleGuy777 wrote:
hi,
I am reading chapter 10 of expert oracle database architecture by tom kyte, and I am getting a little confused. It seems to me as if he is saying that an IOT should be built using the PK of that table. What if our table does not have a PK? Then you can not create an IOT. It's a rule. http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/schema.htm#i23877
One of the suggestions is 'try it'. So let us do exactly that - create 2 nearly idetical IOTs - one with and the second without a primary key
SQL*Plus: Release 10.2.0.1.0 - Production on Sun Nov 1 11:07:37 2009
Copyright (c) 1982, 2005, Oracle. All rights reserved.
Connected to:
Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production
SQL> CREATE TABLE countries_demo
2 ( country_id CHAR(2)
3 CONSTRAINT country_id_nn_demo NOT NULL
4 , country_name VARCHAR2(40)
5 , currency_name VARCHAR2(25)
6 , currency_symbol VARCHAR2(3)
7 , region VARCHAR2(15)
8 , CONSTRAINT country_c_id_pk_demo
9 PRIMARY KEY (country_id ) )
10 ORGANIZATION INDEX
11 /
Table created.
SQL> edit
Wrote file afiedt.buf
1 CREATE TABLE countries_demo2
2 ( country_id CHAR(2)
3 CONSTRAINT country_id_nn_demo NOT NULL
4 , country_name VARCHAR2(40)
5 , currency_name VARCHAR2(25)
6 , currency_symbol VARCHAR2(3)
7 , region VARCHAR2(15) )
8* ORGANIZATION INDEX
SQL> /
ORGANIZATION INDEX
ERROR at line 8:
ORA-25175: no PRIMARY KEY constraint found
SQL>SO the conclusion is, whether it makes sense to us or not, we can not create a table without defining a primary key.
It makes sense to me, since the IOT is actually stored as a unique index with nulls not allowed - for which a PK is a perfect fit. Note that a PK COULD be defined with multiple columns instead of the traditional single column (and often wrong surrogate key) -
Index Vs Primary Key of a table/Internal table
Hello Friends,
What is the difference between Key and Index of a table?
What is the difference between creating an index and specifying "Is Unique" to "Yes" vs creating a Unique Key and specifying "Is Unique" to "Yes"?
Thanks
SimmiHi,
Check these posts:
http://saptechnicalinfo.blogspot.com/2008/08/table-types-in-sap-abap.html
http://blog.sqlauthority.com/2007/04/26/sql-server-difference-between-unique-index-vs-unique-constraint/
http://www.w3schools.com/Sql/sql_create.asp
http://drsql.spaces.live.com/Blog/cns!80677FB08B3162E4!1187.entry
Maybe you are looking for
-
Wired Network conputer cannot find host printer
I cannot print to host printer on a home wired network. Printer is HP Photosmart 7520 e all in one. Host Compter is a Dell Dimension 8100 Pentium 4 1.3 GHz 2.0 GB RAM Windows XP SP3 host computer. Netgear N600 Dual Band Router Model WNDR3400 Network
-
Migration assistant and iphoto
While transferring data from my ibook 3.9 Panther to my new mac mini with firewire migration assistant manually with i think a drag and drop technique, the photos transferred but the albums did not. Same with itunes playlists but not bothered with th
-
Standby archive gap error ..
I have created a standby database,on the same site where my primary database running,every thing works fine,but the problem i am facing is that i am not able to recover my standby database,althogh log transport service archiveing both the dir,primary
-
Where to get WebUtil demo WU_TEST_106.fmb?
Hello! I want to use the WU_TEST_106.fmb file. Where can I download it? Thank you! Ekrem
-
I want to manuel set "bind varaiable" when page on load with ADF BC
hi, I am opening a page from other page, opening page is query page that it must take its bind varaiable from main jspx page on ADF, how can I set bind varaiable for query when the page on load. or how can I qeury according to main page variable.