SQL INTERVIEW PREPARATION PART-16

Data Analytics
Mr. Plan ₿ Publication
1 min readJun 23, 2024

Question 16: What is the difference between a primary key and a unique key in SQL?

Answer:
- Primary Key:
- Uniquely identifies each record in a table.
- Cannot contain NULL values.
- A table can have only one primary key.
- Often automatically creates a clustered index on the column(s).

- Unique Key:
- Ensures that all values in a column or a set of columns are unique across the table.
- Can contain NULL values, but each NULL is considered unique.
- A table can have multiple unique keys.
- Often creates a non-clustered index on the column(s).

Example:
CREATE TABLE employees (
id INT PRIMARY KEY,
email VARCHAR(255) UNIQUE
);
In this example, id is the primary key, ensuring no duplicate values and no NULLs, while email is a unique key, ensuring unique values but allowing NULLs.

Tip: Clarify that the primary key is a more stringent constraint than a unique key because it does not allow NULL values. Emphasize the importance of both constraints in maintaining data integrity and ensuring that records can be uniquely identified.

You can refer these SQL Interview Resources to learn more

Like this post if you want me to continue this SQL series 👍♥️

Share with credits: https://t.me/sqlspecialist

Hope it helps :)

--

--

Data Analytics
Mr. Plan ₿ Publication

Sharing Free Data Science & Data Analytics Projects with best resources | SQL, Python, Power BI, Tableau | Transforming complex data into actionable insights.