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

What is Primary Key Constraint and Unique Key Constraints?

Câu trả lời

In SQL, both Primary Key and Unique Key constraints are used to ensure data uniqueness within a table, but they serve different purposes and have distinct characteristics.

Primary Key Constraint

A primary key is a column or a set of columns that uniquely identifies each row in a table. This constraint has several important characteristics:

  1. Uniqueness: No two rows can have the same primary key value, ensuring that each record can be uniquely identified.
  2. Non-nullability: Primary key columns must be defined with NOT NULL. This ensures that there are no rows without a primary key value, which is essential for the integrity of the identification system within the table.
  3. Indexing: By default, a primary key creates a unique clustered index on the column or columns that are defined as the primary key. This not only enforces uniqueness and non-nullability but also improves performance for queries that use the primary key column(s) for filtering.
  4. Limitation: A table can have only one primary key constraint. This constraint can consist of single or multiple columns (composite key).

Examples of SQL syntax for creating a primary key are as follows:

sql Copy
-- Creating a primary key on a single column during table creation
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    PRIMARY KEY (ID)
);

-- Creating a composite primary key during table creation
CREATE TABLE Orders (
    OrderID int NOT NULL,
    ProductID int NOT NULL,
    OrderDate date NOT NULL,
    PRIMARY KEY (OrderID, ProductID)
);

Unique Key Constraint

A unique key constraint also ensures that all values in a column or a set of columns are unique across the database table. However, it differs from the primary key constraint in the following ways:

  1. Null Values: Unlike primary keys, columns under a unique constraint can accept null values. However, only one null value is allowed if the column is defined as unique.
  2. Non-Clustered Index: By default, a unique constraint creates a non-clustered index on the columns, unlike the clustered index of...
junior

junior

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

middle

Explain the use of FEDERATED tables in MySQL

middle

What are key constraints. What different types of constraints are there in MySQL?

expert

What happens to a trigger in MySQL if an operation which trigger is associated with fails? Does the
trigger execute?

Bình luận

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

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