Câu hỏi phỏng vấn SQL
Câu hỏi

What is PRIMARY KEY ?

Câu trả lời

A PRIMARY KEY in SQL is a constraint that uniquely identifies each record in a database table. It ensures that the values in the primary key column(s) are unique and not null, thereby preventing duplicate and null entries. Here are the key characteristics and functionalities of a primary key:

  1. Uniqueness: Each value in the primary key column(s) must be unique across the table. This ensures that every record can be uniquely identified.
  2. Not Null: Primary key columns cannot contain null values. This is because a null value would not provide a unique identifier for a record.
  3. Single or Composite Key: A primary key can consist of a single column (simple primary key) or multiple columns (composite primary key). When multiple columns are used, the combination of values in these columns must be unique.
  4. One Per Table: Each table can have only one primary key, although this key can be composed of multiple columns.
  5. Index Creation: Defining a primary key automatically creates a unique index on the primary key column(s), which helps in faster data retrieval.

Examples

Creating a Primary Key on a Single Column:

sql Copy
CREATE TABLE Customers (
    CustomerID INT NOT NULL PRIMARY KEY,
    Name VARCHAR(50) NOT NULL,
    Email VARCHAR(50)
);

In this example, CustomerID is the primary key, ensuring that each customer has a unique identifier.

Creating a Composite Primary Key:

sql Copy
CREATE TABLE Orders (
    OrderID INT NOT NULL,
    ProductID INT NOT NULL,
    Quantity INT,
    PRIMARY KEY (OrderID, ProductID)
);

Here, the combination of OrderID and ProductID serves as the primary key, ensuring that each order-product pair is unique.

Adding a Primary Key to an Existing Table:

sql Copy
ALTER TABLE Employees
ADD CONSTRAINT PK_Employees PRIMARY KEY (EmployeeID);

Thi...

entry

entry

Gợi ý câu hỏi phỏng vấn

junior

What is DEFAULT ?

middle

What is the difference between JOIN and UNION ?

entry

What is a VIEW ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào