Pages

Sunday, 16 March 2014

SQL Primary Key Constraint



Although this is not a good way to start a blog, I thought that I would document the scenarios which I have to again and again Google. So it would help to and also some one who Google for help. 

Today I researched about Primary Key constraint in database tables, I know that all of you are very much aware about it, but technically I found that when you want to "Drop" a primary key it is much difficult if you haven't named that constraint. If you have name it you can "Drop" it using that name, but if you didn't name it then it will be a crisis if you are in a situation that you need to "Drop" that constraint. We'll discuss about it later.

First question; what is primary key constraint? Answer is so simple, it is the constraint which identifies a row in a database uniquely. So the value in primary key should be unique, it cannot be duplicated and most importantly it cannot contain NULL values. And at last a table can have only one primary key, but it can be a combination of several columns in that table to make it unique. 

Lets see my recommended way of creating a primary key;

It is very easy to do that; the main concern here is to name your constant using what ever unique name, but if it is something relevant to your table it will helpful to remember constraint later. No worries if you have forgot it, simply you can find it using a simple query as mentioned below;
It will list all the details about your given table, so definitely it includes details about the constraints of the table.

You may add Primary key constraint to your table by Altering it;
How to drop a primary key;


As you seen if you name your primary key constraint it is very easy to drop it whenever you want using its name. If you want to drop unnamed primary key constraint how do it? lets find out.

You may need to replace table name as relevant to you.
I hope that I did something helpful to save your time and effort. If you have any questions please mention them in a comment.

No comments:

Post a Comment