Logo

K-Learn

SQL Primary Key

< Previous Next >

A primary key in SQL is a column or a combination of columns that uniquely identifies each row in a table. It is used to ensure that each row in the table is unique and can be identified with a unique value.

Here is an example to explain Primary Key in sql:

CREATE TABLE student (
  id INT PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  email VARCHAR(50) UNIQUE NOT NULL,
  phone VARCHAR(20),
  address VARCHAR(100)
);

OUTPUT

In this above example,

This statement creates the "student" table with the "id" column as the primary key. By making the "id" column the primary key, we ensure that each row in the table has a unique identifier.

When we insert new data into the "student" table, we must ensure that the "id" column contains a unique value for each row. If we try to insert a new row with a duplicate "id" value, the database will throw an error.

Primary keys are essential in database design, as they allow us to uniquely identify each record in the table and establish relationships between tables. They are used in conjunction with foreign keys to create relationships between tables, which allows us to retrieve and manipulate data from multiple tables at once.

 


< Previous Next >