Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what is difference UNIQUE …, in postgresql?

what is difference UNIQUE, UNIQUE NOT NULL, UNIQUE NULLS DISTINCT, UNIQUE NULLS NOT DISTINCT, in postgresql ?.

CREATE TABLE cus (
  customer_id SERIAL PRIMARY KEY,
  first VARCHAR(20) UNIQUE,
  third VARCHAR(20) UNIQUE NOT NULL,
  fourth VARCHAR(20) UNIQUE NULLS DISTINCT,
  fifth VARCHAR(20) UNIQUE NULLS NOT DISTINCT  
); 

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There are a few variations at play here…

  • UNIQUE means values in that column must be unique (e.g. they can’t be equal). You can then specify how the database should treat uniques:
    • UNIQUE NULLS DISTINCT (default) – treats NULL values as distinct (so you can still have multiple rows with a NULL value in this column). This is the default behavior, so it’s the same as writing UNIQUE alone.
    • UNIQUE NULLS NOT DISTINCT (default) – treats NULL values as if they are equal, so you can at most have one row with a NULL value in that column.
  • NOT NULL is a different modifier that just means that column won’t accept NULL values.

So with those in mind, here is the explained behavior for your examples:

CREATE TABLE cus (
  customer_id SERIAL PRIMARY KEY,
  first VARCHAR(20) UNIQUE,
  -- All values in this column must be unique, but can have multiple nulls
  third VARCHAR(20) UNIQUE NOT NULL,
  -- All values in this column must be unique, nulls not allowed in this column at att
  fourth VARCHAR(20) UNIQUE NULLS DISTINCT,
  -- All values in this column must be unique, but can have multiple nulls (same as first)
  fifth VARCHAR(20) UNIQUE NULLS NOT DISTINCT  
  -- All values in this column must be unique, at most one NULL value allowed
); 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading