Database Research & Development

  • Home
  • NoSQL
    • NoSQL
    • Cassandra
  • Databases
    • Database Theory
    • Database Designing
    • SQL Server Coding Standards
    • SQL Server
    • PostgreSQL
    • MySQL
    • Greenplum
    • Linux
  • Interviews
    • SQL Server Interviews
    • MySQL Interviews
    • SQL Puzzles
  • DBA Scripts
    • SQL Server DBA Scripts
    • PostgreSQL DBA Scripts
    • MySQL DBA Scripts
    • Greenplum DBA Scripts
  • Home
  • Blog Archives !
  • (: Laugh@dbrnd :)
  • Contact Me !
sqlserverinterviews
Home 2016 January PostgreSQL: Composite UNIQUE Constraint does not consider NULL Values

PostgreSQL: Composite UNIQUE Constraint does not consider NULL Values

This article is half-done without your Comment! *** Please share your thoughts via Comment ***

PostgreSQL UNIQUE Constraint does not consider a NULL values for uniqueness.
I am surprised when I found few duplicate values in my database where Unique key constraint already defined for that columns.

I know the thumb rule of UNIQUE Constraint is, UNIQUE Key column can be a NULL.

In my Postgres database, I applied Composite Unique Key in multiple columns, and this constraint failed when one of the value is NULL, and another value is NOT NULL.

Below is a full example on this:

Create a sample table with composite Unique Key:

1
2
3
4
5
6
7
8
9
CREATE TABLE tbl_TestUniqueNull
(
ID INTEGER
,NoA INTEGER
,NoB INTEGER
,NoC INTEGER
,CONSTRAINT pk_tbl_TestUniqueNull_ID PRIMARY KEY(ID)
,CONSTRAINT uk_tbl_TestUniqueNull_NoA_NoB_NoC unique (NoA,NoB,NoC)
);

Now insert few records with the same combination:

1
2
3
4
5
INSERT INTO tbl_TestUniqueNull VALUES (1,1,2,NULL);
INSERT INTO tbl_TestUniqueNull VALUES (2,1,2,NULL);
INSERT INTO tbl_TestUniqueNull VALUES (3,1,5,NULL);
INSERT INTO tbl_TestUniqueNull VALUES (4,3,NULL,1);
INSERT INTO tbl_TestUniqueNull VALUES (5,3,NULL,1);

Postgres Unique Key Null

You can check above result, and we can easily find duplicate combination when one column has a NULL value. Which is wrong and if we have this kind of requirement when we need a composite Unique Key, it fails.

The solution is Unique Index:
In the above situation, we have to use the Unique Index of PostgreSQL.

Create a Unique Index for this example:

1
2
3
CREATE UNIQUE INDEX UIdx_NoA_NoB_NoC
ON tbl_TestUniqueNull
(coalesce(NoA,-1),coalesce(NoB,-1),coalesce(NoC,-1));
When you try to insert duplicate combination after applying this index, you will get a below error message.

1
2
3
4
5
6
7
ERROR: duplicate key value violates unique constraint "uidx_noa_nob_noc"
DETAIL: Key ((COALESCE(noa, (-1))), (COALESCE(nob, (-1))), (COALESCE(noc, (-1))))=(3, -1, 1) already exists.
********** Error **********
 
ERROR: duplicate key value violates unique constraint "uidx_noa_nob_noc"
SQL state: 23505
Detail: Key ((COALESCE(noa, (-1))), (COALESCE(nob, (-1))), (COALESCE(noc, (-1))))=(3, -1, 1) already exists.

Jan 18, 2016Anvesh Patel
MySQL: Configured InnoDB Engine for Multithreaded DatabaseSQL Server: Remove recent file history from the File Menu
Comments: 8
  1. PISEY
    February 1, 2016 at 8:16 am

    Ples check ur ERROR message again , the ERROR message shown you :

    ERROR: duplicate key value violates unique constraint “pk_tbl_testuniquenull_id”
    DETAIL: Key (id)=(5) already exists.

    this is violates unique primary key constraint not composite unique constraint(NoA,NoB,NoC) caused you insert number 5 two times to primary key column, so mean that your Partial Unique Index is not work here.

    • PISEY
      February 1, 2016 at 8:41 am

      create table uktb(col1 int,col2 int,col3 int,constraint ukc unique (col1,col2,col3));

      create unique index prvuk on uktb (coalesce(col1,-1),coalesce(col2,-1),coalesce(col3,-1));

      insert into uktb values(1,2,null);
      INSERT 0 1
      insert into uktb values(1,2,null);
      ERROR: duplicate key value violates unique constraint “prvuk” ….

    • Anvesh Patel
      Anvesh Patel
      February 2, 2016 at 4:30 am

      Thanks Pisey for your observation, I have done some mistake on this demo and as per your suggestion I have updated this article.
      Thank you very much ! šŸ™‚

      • PISEY
        February 12, 2016 at 2:11 am

        you’re welcome, you give me more than i give u , i always follow your demo because i am just a new dba. most of your article is useful for me.

        • Anvesh Patel
          Anvesh Patel
          February 12, 2016 at 4:28 am

          Thank you Very much and Next week on wards, I am going to start RND on NOSQL Technology.
          You will also like this.

  2. Mohammaed
    April 12, 2016 at 3:19 am

    Hi there all, here every person iis shwring these experience, thus it’s good too read this
    website, and I used to visit this blog everyday.

  3. Luce
    May 18, 2016 at 10:21 pm

    This website was… how do I say it? Relevant!! Finally I have found something which
    helped me. Appreciate it!

  4. Syed Anjum
    August 23, 2016 at 2:21 am

    The reason of the accepting the values as you said is that null is never equal to another null;
    Mathematically null null;
    It is because of that the value has been accepted as per my understating.

    Note: i made a mistake in posting my previous post. when i forget to make null null.

Anvesh Patel
Anvesh Patel

Database Engineer

January 18, 2016 PostgreSQLAnvesh Patel, database, database research and development, dbrnd, Partial Index, plpgsql, Postgres Query, postgresql, PostgreSQL Administrator, PostgreSQL Error, PostgreSQL Programming, PostgreSQL Tips and Tricks, UNIQUE, Unique Index
About Me!

I'm Anvesh Patel, a Database Engineer certified by Oracle and IBM. I'm working as a Database Architect, Database Optimizer, Database Administrator, Database Developer. Providing the best articles and solutions for different problems in the best manner through my blogs is my passion. I have more than six years of experience with various RDBMS products like MSSQL Server, PostgreSQL, MySQL, Greenplum and currently learning and doing research on BIGData and NoSQL technology. -- Hyderabad, India.

About DBRND !

dbrnd

This is a personal blog (www.dbrnd.com).

Any views or opinions represented in this blog are personal and belong solely to the blog owner and do not represent those of people, institutions or organizations that the owner may or may not be associated with in professional or personal capacity, unless explicitly stated.

Feel free to challenge me, disagree with me, or tell me I’m completely nuts in the comments section of each blog entry, but I reserve the right to delete any comment for any reason whatsoever (abusive, profane, rude, or anonymous comments) - so keep it polite.

The content of this website is protected by copyright. No portion of this website may be copied or replicated in any form without the written consent of the website owner.

Recent Comments !
  • Anvesh Patel { Sure will do... } – May 27, 12:43 PM
  • Anvesh Patel { Great... } – May 27, 12:41 PM
  • Anvesh Patel { Great... } – May 27, 12:39 PM
  • Anvesh Patel { Great... } – May 27, 12:36 PM
  • Anvesh Patel { Great... } – May 27, 12:28 PM
  • Anvesh Patel { Great... } – May 27, 12:27 PM
  • Anvesh Patel { Great... } – May 27, 12:16 PM
  • Older »
Follow Me !
  • facebook
  • linkedin
  • twitter
  • youtube
  • google
  • flickr
Ā© 2015 – 2019 All rights reserved. Database Research & Development (dbrnd.com)
Posting....