Interview Question of the Week #010 – What is the Difference Between Primary Key Constraints and Unique Key Constraints?

I often see primary keys and unique constraints treated as the same thing. They both enforce uniqueness, but this interview question has two important differences.

One locked garden gate beside another gate with several keys

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

Answer: A table has one primary key. Its key columns cannot be NULL. A table can have other unique constraints for alternate business keys, and a unique constraint can be defined on a nullable column. For a single nullable column, SQL Server permits one NULL under an ordinary unique constraint, not unlimited NULL rows.

The index detail often comes up as a follow-up. SQL Server enforces both kinds of constraint with a unique index. A primary key commonly gets a clustered index by default when the table has none; a unique constraint commonly gets a nonclustered index. These are defaults, not definitions. You can explicitly make the primary key nonclustered, and the table still has exactly one primary key.

I start with the data rule, then discuss the physical index choice. If an interviewer answers only “one is clustered and the other is nonclustered,” I would ask them to think about a primary key declared NONCLUSTERED. That small counterexample reveals the real distinction.

For a longer treatment, see my earlier notes on primary and unique constraints and on a nonclustered primary key.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

Previous Post
Interview Question of the Week #009 – Is GO T-SQL Statement?
Next Post
Interview Question of the Week #011 – Script to Convert List to Table and Table to List

Related Posts

No results found.

1 Comment. Leave new

  • Roman Rapido
    May 19, 2016 4:32 am

    How do I Create Custom Primary Key for Multi-user Point of sale application? I need to create custom PK because I want to export and import data to a main location, the source would be the store branches, I export from the Branches and Import on the main sql server

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.