KEY

KEY in SQL is a tool that enforces certain type of uniqueness, in other words it ensures that the data within a column or set of columns is distinct. It usually serves either as a primary key that uniquely identifies each row of data in a table, or as a foreign key, establishing relationships between tables based on matching column values.

Example

CREATE TABLE Students (
StudentID int,
StudentName varchar(255),
Age int,
PRIMARY KEY (StudentID)
);
INSERT INTO Students (StudentID, StudentName, Age)
VALUES (1, 'John Doe', 18), (2, 'Jane Doe', 20);
SELECT * FROM Students;

Output

+-----------+-------------+-----+
| StudentID | StudentName | Age |
+-----------+-------------+-----+
| 1 | John Doe | 18 |
| 2 | Jane Doe | 20 |
+-----------+-------------+-----+

Explanation

In the given example, a new table ‘Students’ is created with three fields - StudentID, StudentName, and Age. Among these, StudentID is defined as PRIMARY KEY. This key uniquely identifies each record in the table. Two rows of data are then inserted into the table. The SELECT * FROM Students query is used to display all the records from the Students table.

Example

CREATE TABLE Employee (
ID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Age INT NOT NULL,
Address VARCHAR(255)
);
INSERT INTO Employee (ID, Name, Age, Address)
VALUES (1, 'John Doe', 30, '123 Main St');

Output

Command(s) completed successfully.

Explanation

In the given example, a table named ‘Employee’ was created with columns ‘ID’, ‘Name’, ‘Age’, and ‘Address’. The column ‘ID’ was identified as the PRIMARY KEY, which is a type of constraint used in SQL Server to uniquely identify each record. Then, one record was inserted into the ‘Employee’ table.

Example

CREATE TABLE Department (
DeptNo NUMBER,
DeptName VARCHAR(50),
Location VARCHAR(50),
PRIMARY KEY (DeptNo)
);

Output

Table DEPARTMENT created.

Explanation

In the example above, the CREATE TABLE statement is used to create a table named Department with the fields DeptNo, DeptName, and Location. The PRIMARY KEY constraint is defined on the DeptNo column meaning that each value in this column must be unique and not null. This constraint serves to uniquely identify each record within the table.

Example

CREATE TABLE Customers (
ID INT PRIMARY KEY,
NAME TEXT NOT NULL
);
INSERT INTO Customers (ID, NAME) VALUES(1, 'John Doe');

Output

Query OK, 1 row affected (0.01 sec)

Explanation

The above code creates a table “Customers” with two fields: “ID” and “NAME”. The “ID” field is defined as the PRIMARY KEY. A primary key is a unique identifier for each record in a table, no two records in the table can have the same key value. An INSERT statement is then used to add a record with ID “1” and NAME “John Doe” into the “Customers” table. The output shows the successful execution of the insert statement.

For in-depth explanations and examples SQL keywords where you write your SQL, install our extension.