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
Output
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
Output
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
Output
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
Output
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.