0 votes
in Sql by
What is a Primary Key?

2 Answers

0 votes
by

The PRIMARY KEY constraint uniquely identifies each row in a table. It must contain UNIQUE values and has an implicit NOT NULL constraint.

A table in SQL is strictly restricted to have one and only one primary key, which is comprised of single or multiple fields (columns).

CREATE TABLE Students ( /* Create table with a single field as primary key */

    ID INT NOT NULL

    Name VARCHAR(255)

    PRIMARY KEY (ID)

);

CREATE TABLE Students ( /* Create table with multiple fields as primary key */

    ID INT NOT NULL

    LastName VARCHAR(255)

    FirstName VARCHAR(255) NOT NULL,

    CONSTRAINT PK_Student

    PRIMARY KEY (ID, FirstName)

);

ALTER TABLE Students /* Set a column as primary key */

ADD PRIMARY KEY (ID);

ALTER TABLE Students /* Set multiple columns as primary key */

ADD CONSTRAINT PK_Student /*Naming a Primary Key*/

PRIMARY KEY (ID, FirstName);

Q   =>   Write a SQL statement to add PRIMARY KEY 't_id' to the table 'teachers'.

Q   =>   Write a SQL statement to add primary key constraint 'pk_a' for table 'table_a' and fields 'col_b, col_c'.

0 votes
by

A primary key is a field or the combination of fields that uniquely identify each record in the table. It is one of a special kind of unique key. If the column contains a primary key, it cannot be null or empty. A table can have duplicate columns, but it cannot have more than one primary key. It always stores unique values into a column. For example, the ROLL Number can be treated as the primary key for a student in the university or college.

SQL Interview Questions and Answers

We can define a primary key into a student table as follows:

CREATE TABLE Student (    

    roll_number INT PRIMARY KEY,    

    name VARCHAR(45),     

);    

To read more information, click here.

Related questions

0 votes
asked Jun 12, 2023 in Sql by Robin
0 votes
asked Jul 12, 2020 in Sql by Robindeniel
...