Primary Key of SQL Server

Source: Internet
Author: User
Tags sql primary key
Document directory
  • SQL Server:
  • For MySQL/SQL Server/Oracle/MS access:
  • For MySQL/SQL Server/Oracle/MS access:
  • MySQL:
  • SQL Server/Oracle/MS access:
SQL primary key constraints

The primary key constraint uniquely identifies each record in the database table.

The primary key must contain a unique value.

The primary key column cannot contain null values.

Each table should have a primary key, and each table can have only one primary key.

SQL Server:
CREATE TABLE Persons(Id_P int NOT NULL PRIMARY KEY,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))

To name the primary key constraint and define the primary key constraint for multiple columns, use the following SQL Syntax:

CREATE TABLE Persons(Id_P int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CONSTRAINT uc_PersonID PRIMARY KEY (Id_P,LastName))
SQL primary key constraint on ALTER TABLE

If you create a primary key constraint for the "id_p" column when the table already exists, use the following SQL statement:

For MySQL/SQL Server/Oracle/MS access:
ALTER TABLE PersonsADD PRIMARY KEY (Id_P)

To name the primary key constraint and define the primary key constraint for multiple columns, use the following SQL Syntax:

For MySQL/SQL Server/Oracle/MS access:
ALTER TABLE PersonsADD CONSTRAINT pk_PersonID PRIMARY KEY (Id_P,LastName)

Note: If you use the alter table statement to add a primary key, you must declare that the primary key column does not contain null.
Value (when the table is created for the first time ).

Revoke the primary key constraint

To revoke the primary key constraint, use the following SQL statement:

MySQL:
ALTER TABLE PersonsDROP PRIMARY KEY
SQL Server/Oracle/MS access:
ALTER TABLE PersonsDROP CONSTRAINT pk_PersonID
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.