PRIMARY KEY
PRIMARY KEY in SQL refers to a constraint that can be applied to a column or set of columns in a table, establishing a unique identifier for each record within the table. This constraint enforces the uniqueness and guarantee that the column(s) do not accept NULL values. It is often used to set a primary key for the table.
Example
CREATE TABLE Employees ( ID int, Name varchar(255), Age int, Address varchar(255), Salary int, PRIMARY KEY (ID));
Output
Query OK, 0 rows affected (0.21 sec)
Explanation
This SQL command creates a table named ‘Employees’ with five fields: ID, Name, Age, Address, Salary. The ID field is defined as the PRIMARY KEY. This means that every record in the table must have a unique ID.
Example
CREATE TABLE Students ( Student_ID INT PRIMARY KEY, First_Name VARCHAR(40) NOT NULL, Last_Name VARCHAR(40) NOT NULL);
Output
QUERY OK, 0 rows affected (0.01 sec)
Explanation
The above command creates a table Students
with three columns - Student_ID
, First_Name
, and Last_Name
. The Student_ID
is specified as the PRIMARY KEY
, which uniquely identifies each record in the table. No two records can have the same Student_ID
and this column cannot contain NULL values.
Example
CREATE DATABASE TestDB;GO
USE TestDB;GO
CREATE TABLE Employees ( ID INT PRIMARY KEY, Name NVARCHAR(50) NOT NULL,);GO
Output
Command(s) completed successfully.
Explanation
In the example, a new database, TestDB
, is created, and a new table, Employees
, is created within that database. The Employees
table contains two columns, ID
and Name
. The ID
column is designated as the primary key for the table. This is indicated by the PRIMARY KEY
declaration following the ID INT
statement. The primary key is a unique identifier for each record in the table.
Example
CREATE TABLE Customers ( CustomerID int NOT NULL PRIMARY KEY, FirstName varchar(255), LastName varchar(255), City varchar(255));
Output
Table CUSTOMERS created.
Explanation
In the provided example, a new table named ‘Customers’ is created with four columns: CustomerID
, FirstName
, LastName
, and City
. Here, CustomerID
is set as a PRIMARY KEY
, which uniquely identifies each record in the database table.
Example
CREATE TABLE Students ( ID INT PRIMARY KEY, NAME TEXT,);INSERT INTO Students(ID, NAME) VALUES (1, 'John');
Output
Query OK, 0 rows affected (0.01 sec)
Explanation
In the given example, the Students
table is created with ID
and NAME
columns. The ID
column is defined as the PRIMARY KEY
. This implies that the ID
column cannot hold duplicate or null values. After defining the table, a row containing the values (1, 'John')
is inserted.