add data into primary key [duplicate] - sql

This question already has answers here:
Oracle SQL - Add Primary Key to table
(2 answers)
Closed 5 years ago.
this is my table.In this table i want to add a primary key column name "emp_id" as the first column .I don't know how to do it .So,can you please help me!
EMP_NAME EMP_POS SALARY GENDER
----------------- ----------------- -------------- ------
anand worker 10000 M
balu manager 50000 M
carl manager 50000 M
riya md 60000 F
prabhu owner 99999999 M

The old way of doing this is a multi-step process:
add the column which will be the primary key
update the column
enforce the primary key.
Something like this:
create sequence t23_id;
alter table t23 add id number;
update t23
set id = t23_id.nextval
;
alter table t23 add constraint t23_pk primary key (id);
In 12c Oracle added Identity columns (like SQL Server auto-incrementing columns). This reduces the number of steps to two:
alter table t23i add id number GENERATED ALWAYS AS IDENTITY primary key;
alter table t23i add constraint t23i_pk primary key (id);
Unfortunately it can't be done in one step. This ...
alter table t23i add id number GENERATED ALWAYS AS IDENTITY primary key;
...hurls ...
ORA-01758: table must be empty to add mandatory (NOT NULL) column
Livesql demo

Introduce identity column:
see http://sql-plsql.blogspot.sg/2014/11/add-identity-column-to-table.html
Reorder the columns:
see http://www.dba-oracle.com/t_change_column_order_within_oracle_table.htm
Hope these references help.

Related

Primary key is not deleted when I deleted table inside SSMS- SQL Server

I have a table and I need to insert a huge number of records, so I create my table without primary key to make the insert faster. when I finished insert, I create primary key for that table using this command:
ALTER TABLE MyTable ADD CONSTRAINT PK_MyTable PRIMARY KEY (MyTableId)
The problem is if I delete the table inside SQL Server management studio then the next time when I want to create this primary key, it says :
The CREATE UNIQUE INDEX statement terminated because
a duplicate key was found for the object name
I need to let SQL knows that this primary key is connected to that table and must automatically be deleted when the table is being deleted.
I guess this is not a primary key problem. It is a problem with your data. You are not allowed to create a primary key because you have a duplicate value in your primary key column.
You could run a query to confirm that you have a duplicate.
SELECT
MyTableId,
COUNT(*)
FROM
MyTable
GROUP BY
MyTableId
HAVING
COUNT(*) > 1
The Best Answer to dropping the table containing Primary and foreign constraints is :
Step 1 : Drop the Primary key of the table.
Step 2 : Now it will prompt whether to delete all the foreign references or not.
Step 3 : Delete the table.

More than one unique key in a table [duplicate]

This question already has answers here:
Unique constraint on multiple columns
(4 answers)
Closed 5 years ago.
I have a Product table in my DB with following columns :
ProductId INT IDENTITY PRIMARY KEY
ProductCode VARCHAR(100) NOT NULL
ProductStamp VARCHAR(100) NOT NULL
I need both ProductCode and ProductStamp unique for example :
Allowed
Code Stamp
---- -----
A001 S001
A002 S002
Not allowed
Code Stamp
---- -----
A001 S001
A001 S002
How to achieve this? Thank you very much
Unique constraint on a single column:
ALTER TABLE Product ADD CONSTRAINT AK_Product_ProductCode UNIQUE( ProductCode )
ALTER TABLE Product ADD CONSTRAINT AK_Product_ProductStamp UNIQUE( ProductStamp )
These will raise an error if there are two rows with duplicate product codes, OR product stamps.
Unique constraint on a multiple columns:
ALTER TABLE Product ADD CONSTRAINT AK_Product_ProductCodeAndStamp UNIQUE( ProductCode, ProductStamp )
This will fire if there are two rows with code AND stamp the same.
The convention "AK" for naming stands for "Alternate Key"
You need to add a Unique Index:
CREATE UNIQUE NONCLUSTERED INDEX [IX_NAME] ON [your_table]
(
ProductCode
) WITH IGNORE_DUP_KEY;
Based on your needs, I would recommend using a unique constraint or unique index to the column(s) you need uniqueness enforced by the database.
Note that a unique constraint is not indexed in any way, so if you have a lot of use for the unique columns in where clauses (or in joins), you will probably want to use an index.
If not, a unique constraint would be better in terms of storage size and insert/update costs.

Oracle SQL - Add Primary Key to table

I have some columns with no primary key and want to add a primary key column.
NAME Age
-------------
Peter 45
Bob 25
John 56
Peter 45
Some collegues suggest to add a PK with a sequences and triggers:
Add a auto increment primary key to existing table in oracle
This is nice, but my customers use a Database User with no rights to add sequences or triggers.
I want to prevent to contact dozens of DBA administrators to alter user rights or to run my scripts.
This is my suggestion to add a PK with only an update statement: (I need help in Step 2)
Step 1: Create the ID column (I have DB rights for this)
ALTER TABLE PERSON ADD ID NUMBER(10,0);
Step 2: Question: Can I initialize the ID column with unique values based on the order of the rows or something else? How?
UPDATE PERSON SET ID = something-unique
Step 3: Add the primary key contraint afterwords: (I DB have rights for this)
ALTER TABLE PERSON ADD CONSTRAINT PK_ID PRIMARY KEY(ID);
Step 4: Afterwords: the primary key is managed and added by my application.
This will be the result:
ID(PK) NAME Age
---------------------
1 Peter 45
2 Bob 25
3 John 56
4 Peter 45
Thanks folks!
Update person set id = rownum;
THis idea is very childish, but should work fine if your table doesnot have large amount of rows.
For step 2, run a for loop like:
declare
i pls_integer :=1;
begin
for rec in (select name,age, rowid from table_name)
loop
update table_name set id = i
where
table_name.name=rec.name
and table_name.age=rec.age
and table_name.rowid = rec.rowid;
i:=i+1;
end loop;
end;

Adding column with primary key in existing table

I am trying to add primary key to newly added column in existing table name Product_Details.
New Column added: Product_Detail_ID (int and not null)
I am trying add primary key to Product_Detail_ID (please note: there are no other primary or foreign key assigned to this table)
I am trying with this query but getting error.
ALTER TABLE Product_Details
ADD CONSTRAINT pk_Product_Detils_Product_Detail_ID PRIMARY KEY(Product_Detail_ID)
GO
Error:
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'dbo.Product\_Details' and the index name 'pk\_Product\_Detils'. The duplicate key value is (0).
Am I missing something here? I am using SQL Server 2008 R2. I would appreciate any help.
If you want SQL Server to automatically provide values for the new column, make it an identity.
ALTER TABLE Product_Details DROP COLUMN Product_Detail_ID
GO
ALTER TABLE Product_Details ADD Product_Detail_ID int identity(1,1) not null
GO
ALTER TABLE Product_Details
add CONSTRAINT pk_Product_Detils_Product_Detail_ID primary key(Product_Detail_ID)
GO
In mysql, I was able to achieve with following query
ALTER TABLE table_name ADD new_column int NOT NULL AUTO_INCREMENT primary key
Add Primary Key to First Position
ALTER TABLE table_name
ADD column_name INT PRIMARY KEY AUTO_INCREMENT FIRST;
Reference: Stack Overflow | Tech On The Net
You are getting the error because you have existing data that does not fullfill the constraint.
There are 2 ways to fix it:
clean up the existing data before adding the constraint
add the constraint with the "WITH NOCHECK" option, this will stop sql server checking existing data, only new data will be checked
ALTER TABLE Jaya
ADD CONSTRAINT no primary key(No);
here Jaya is table name,
no is column name,
ADD CONSTRAINT is we giving the primary key keyword
If you want to add a new column say deptId to the existing table say department then you can do it using the below code.
ALTER TABLE department ADD COLUMN deptID INT;
it will create your new column named deptID.
now if you want to add constraint also along with new column while creating it then you can do it using the below code. In the below code I am adding primary key as a constraint. you can add another constraint also instead of primary key like foreign key, default etc.
ALTER TABLE department ADD COLUMN deptID INT NOT NULL ADD CONSTRAINT PRIMARY KEY(deptID);
k. friend
command:
sql> alter table tablename add primary key(col_name);
ex: alter table pk_Product_Detils add primary key(Product_Detail_ID);

ORA-02437: cannot validate <name> - primary key violated

I have a table:
CREATE TABLE MY_TABLE (
MY_ID NUMBER NOT NULL,
COLUMN_1 NUMBER,
COLUMN_2 NUMBER
);
ALTER TABLE MY_TABLE ADD CONSTRAINT PK_FOO PRIMARY KEY (MY_ID);
at a later point, when executing the following sql, I get an error:
ALTER TABLE MY_TABLE DROP PRIMARY KEY DROP INDEX;
ALTER TABLE MY_TABLE ADD CONSTRAINT PK_FOO PRIMARY KEY (MY_ID)
ORA-02437: cannot validate PK_FOO - primary key violated
My table only contains 3 entries all with a different primary key which is also not null.
Anyone has an idea what this could be?
Thanks,
Peter
My table only contains 3 entries all with a different primary key which is also not null.
You must forgive a certain amount of scepticism on our part. Because that error definitely indicates a duplicate value.
What you need to do is use the exceptions clause. This will show you the ROWIDs of the records which are violating your constraint. You may need to create the target table: by default the script creates a table called EXCEPTIONS:
SQL> ALTER TABLE MY_TABLE ADD CONSTRAINT PK_FOO PRIMARY KEY (MY_ID);
ALTER TABLE MY_TABLE ADD CONSTRAINT PK_FOO PRIMARY KEY (MY_ID)
*
ERROR at line 1:
ORA-02437: cannot validate (APC.PK_FOO) - primary key violated
SQL> #%ORACLE_HOME%\rdbms\admin\utlexpt1.sql
Table created.
SQL> ALTER TABLE MY_TABLE ADD CONSTRAINT PK_FOO PRIMARY KEY (MY_ID)
2 exceptions into exceptions
3 /
ALTER TABLE MY_TABLE ADD CONSTRAINT PK_FOO PRIMARY KEY (MY_ID)
*
ERROR at line 1:
ORA-02437: cannot validate (APC.PK_FOO) - primary key violated
SQL> select * from exceptions
2 /
ROW_ID OWNER TABLE_NAME CONSTRAINT
------ ----- ---------- ----------
AABQXcAAEAAAXUPAAD APC MY_TABLE PK_FOO
AABQXcAAEAAAXUPAAB APC MY_TABLE PK_FOO
SQL>
Edit
You need to figure out what is different between your install code and the simplification you posted here. The chances are you have one or more INSERT statements which are accidentally executed more than once while the constraint is not in force. Adding the EXCEPTIONS INTO clause to your code might help you track it down.
from here
Cause: You tried to tried to enable a
primary key constraint, but the
columns in the primary key either
contained NULL values or duplicates..
The maim reason of violation of primary ki is the atrrbute you making is nullable or you have some dupliactes in table for that id or attribute
create table client_master
(
client_no varchar2(6),
client_name varchar2(20),
city varchar2(25),
state varchar2(15),
pin number(6),
balance_due number(10,2));
for e.g,
after inserting values
0008 Mukul NYCT NYC 199560 2500
0006 Rukmini bombay maharastra 100001 0
0007 Krishna mathura up 900050 100000
0008 Mukul NYCT NYC 199560 2500
or your id is nullable
so just MODIFY THE ATTRIBUTE is and set to NOT NULL
also remove duplicates if any
DELETE client_master
WHERE rowid NOT IN
(SELECT MAX(rowid)
FROM client_master
GROUP BY client_no,client_name,city,state,pin,balance_due);
then you we will be able to add primary key to client _no
Are 2 primary keys identical?
This error is usually thrown when you try to create/enable a primary key on a table
I'm upvoting APC's answer, but since you seem to have some problems implementing it, could you just post the results of this query:
select my_id, count(*) from my_table group by my_id having count(*) >1
This will give us (and you) some idea of the problematic keys.