sql - primary key

First, the primary key

1. Definitions

The primary key (primary key) one (or set of columns) , the value of each row can be uniquely distinguished table.
In the column uniquely identify each row (or column of the set) is called the primary key. No primary key, update or delete specific rows in the table is very difficult, because there is no safe way to ensure that only design-related lines.

 

2. serve as the primary key condition

No two rows can have the same primary key value.

Each row must have a primary key (primary key column does not allow NULL value).

 

3. Create, add, delete the primary key

(1) direct primary key is created when a new table

CREATE TABLE table_test(

id INT NOT NULL,

name VARCHAR(20) NOT NULL,

address VARCHAR(20),

PRIMARY KEY(id)

);

Create composite key (2) new table (the primary key field can not contain NULL).

CREATE TABLE table_test(

user_id INT NOT NULL,

user_name VARCHAR(20) NOT NULL,

user_address VARCHAR(20),

PRIMARY KEY (user_id, user_name)

);

(3) create a primary key for the table has been built (the primary key column must not be NULL)

CREATE TABLE table_test(

id INT NOT NULL,

name VARCHAR(20) NOT NULL,

address VARCHAR(20)

);

ALTER TABLE table_test ADD PRIMARY KEY (id);

(4) the table has been built to create a composite key (primary key field can not contain NULL)

CREATE TABLE table_test(

user_id INT NOT NULL,

user_name VARCHAR(20) NOT NULL,

user_address VARCHAR(20)

);

ALTER TABLE table_test ADD CONSTRAINT id PRIMARY KEY (user_id, user_name);

Or alter table add constraint primary key table name primary key (1 field names, field names 2 ......) -

Or alter table add constraint primary key table name primary key NONCLUSTERED (1 field names, field names ...... 2)   addition of non-aggregated primary key index

(5) Drop Primary

ALTER TABLE table_test DROP PRIMARY KEY ;

Alter table or drop constraint table primary key name

 

4.SQL difference constraint and a unique primary key constraint

Primary key constraint is not empty, the only constraint may be empty. But both duplicate values ​​are not allowed.

Guess you like

Origin www.cnblogs.com/aczy/p/10923812.html