PRIMARY KEY
Example
Section titled “Example”CREATE TABLE Employees ( ID int, Name varchar(255), Age int, Address varchar(255), Salary int, PRIMARY KEY (ID));Output
Section titled “Output”Query OK, 0 rows affected (0.21 sec)Explanation
Section titled “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
Section titled “Example”CREATE TABLE Students ( Student_ID INT PRIMARY KEY, First_Name VARCHAR(40) NOT NULL, Last_Name VARCHAR(40) NOT NULL);Output
Section titled “Output”QUERY OK, 0 rows affected (0.01 sec)Explanation
Section titled “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
Section titled “Example”CREATE DATABASE TestDB;GO
USE TestDB;GO
CREATE TABLE Employees ( ID INT PRIMARY KEY, Name NVARCHAR(50) NOT NULL,);GOOutput
Section titled “Output”Command(s) completed successfully.
Explanation
Section titled “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
Section titled “Example”CREATE TABLE Customers ( CustomerID int NOT NULL PRIMARY KEY, FirstName varchar(255), LastName varchar(255), City varchar(255));Output
Section titled “Output”Table CUSTOMERS created.Explanation
Section titled “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
Section titled “Example”CREATE TABLE Students ( ID INT PRIMARY KEY, NAME TEXT,);INSERT INTO Students(ID, NAME) VALUES (1, 'John');Output
Section titled “Output”Query OK, 0 rows affected (0.01 sec)Explanation
Section titled “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.