What is difference between Primary key and Unique Key

Carvia Tech | May 20, 2019 | 2 min read | 8 views


Primary key and Unique key are used for different purpose and they can be distinguished based on multiple parameters: their purpose, mutability, existence, nullability and indexes.

Purpose

The main purpose of a Primary key is to uniquely identifies a given record in a Table, while the Unique Key constraint is meant to prevent duplicate values in a column (with exception of null value)

Mutability

Primary keys are immutable and not supposed to be altered, while unique keys can be changed or deleted.

Existance

A table can have one and only one Primary Key (can be composed of single/multiple columns), while there could be multiple unique keys for a single table.

Nullability

Primary Key can not have Null values while Unique key column can contain a Null value. MySql, for example allows multiple null values for a unique key column, while SQL Server allows only a single record with a null value column.

Indexes

By default SQL engine creates a Clustered Index on primary key and a Non-Clustered Index for unique key columns. In clustered index, records of table are physically ordered by primary key so that searching becomes easy using the primary key.

Creating a Primary Key in JPA

Creating a primary key using JPA requires annotating the column with @Id annotation, as shown in the following code:

Creating a Primary Key
@Entity
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

This will create a product table in relational database with id as the primary key.

Creating a Unique Key in JPA

JPA provides multiple ways to create Unique keys on a table.

Lets create a unique constraint on combination of sku and name columns.

Adding Unique Constraint
@Entity
@Table(name = "product", uniqueConstraints = @UniqueConstraint(columnNames = {"name", "sku"})}) (1)
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String sku;
    private String name;

    @Column(unique=true)    (2)
    private String slug;
1 sku and name combination will be unique
2 slug column will be unique

Important point to note here is that UniqueConstraint annotation creates unique constraint on the combined value of name and sku field, instead of creating two unique constraints on name and sku column separately.

We can in fact create multiple unique constraints on a table using array syntax, like this:

@Table(name="product",  uniqueConstraints={
   @UniqueConstraint(columnNames={"name", "sku"}),
   @UniqueConstraint(columnNames={"anotherField", "sku"})
})

If the requirement is just to create a unique constraint over a single column, you should prefer to use @Column(unique=true) for the sake of its simplicity.

That’s all!


Buy my ebook for complete question bank

Most of these questions has been answered in my eBook "Cracking the Core Java Interview" updated on June 2018, that you can buy from this link:

Buy from Shunya (DRM Free PDF download with updates)

Top articles in this category:
  1. Java Concurrency Interview Questions and Answers
  2. Cracking core java interviews - question bank
  3. Top 30 Hibernate and Spring Data JPA interview questions
  4. Top 50 Multi-threading Java Interview Questions for Investment Bank
  5. Goldman Sachs Java Interview Questions for Senior Developer
  6. RBS Java Programming Interview Questions
  7. UBS Top 10 Java Interview Questions


Find more on this topic:
Java Interviews image
Java Interviews

Interview - Product Companies, eCommerce Companies, Investment Banking, Healthcare Industry, Service Companies and Startups.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info