TRENDING TOPICS

×

SQL PRIMARY KEY Constraint

The PRIMARY KEY Constraint is a special single field that used to uniquely defines all records in a table.

PRIMARY KEY Constraint

  • A PRIMARY KEY must contain a unique values for each row of data in a SQL table.
  • The PRIMARY KEY can not contain NULL values.

PRIMARY KEY - CREATE TABLE [MySQL]

CREATE TABLE STUDENTS (
  ID INT   NOT NULL,
  FULL_NAME VARCHAR (200)   NOT NULL,
  ADDRESS VARCHAR (200),
  CITY VARCHAR (200),
  COUNTRY VARCHAR (200)   NOT NULL,
  PRIMARY KEY (ID)
);

PRIMARY KEY - CREATE TABLE [SQL/Oracle/MS Access]

CREATE TABLE STUDENTS (
  ID INT   NOT NULL PRIMARY KEY,
  FULL_NAME VARCHAR (200)   NOT NULL,
  ADDRESS VARCHAR (200),
  CITY VARCHAR (200),
  COUNTRY VARCHAR (200)   NOT NULL
);

ALTER TABLE - PRIMARY KEY

ALTER TABLE STUDENTS
ADD PRIMARY KEY (ID);

PRIMARY KEY - Multiple Columns

A table can have only one PRIMARY KEY but this Primary Key can consist of single or multiple columns.

CREATE TABLE STUDENTS (
  ID INT   NOT NULL,
  FULL_NAME VARCHAR (200)   NOT NULL,
  ADDRESS VARCHAR (200),
  CITY VARCHAR (200),
  COUNTRY VARCHAR (200)   NOT NULL,
  CONSTRAINT PK_Student PRIMARY KEY (ID, FULL_NAME)
);

ALTER TABLE - [PK] Multiple Column

ALTER TABLE STUDENTS
ADD CONSTRAINT PK_Student PRIMARY KEY (ID, FULL_NAME);

© 2021 GDATAMART.COM (All Rights Reserved)