Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres Unique Constraint on two columns: Integer and Boolean

I would like to find a way to store multiple addresses for one subject in my database, with only one default address per subject.

To cut a long story short, lets say we have a table:

CREATE TABLE test
(
  id integer NOT NULL,
  active boolean NOT NULL,
  CONSTRAINT pk_id PRIMARY KEY (id)
)

For each id in the table, there must be at most 1 true active value.

How could I achieve this?

Thanks.

like image 248
greatkalu Avatar asked Jun 13 '12 12:06

greatkalu


People also ask

How do you make two columns unique in PostgreSQL?

The syntax for creating a unique constraint The below illustrations are used to create a Unique constraint with the ALTER TABLE command in PostgreSQL: ALTER TABLE table_name. ADD CONSTRAINT [ constraint_name ] UNIQUE(column_list);

What is the difference between unique index and unique constraint?

A unique index ensures that the values in the index key columns are unique. A unique constraint also guarantees that no duplicate values can be inserted into the column(s) on which the constraint is created. When a unique constraint is created a corresponding unique index is automatically created on the column(s).

Can Unique Key have multiple NULL values in PostgreSQL?

While the SQL standard allows multiple nulls in a unique column, and that is how Postgres behaves, some database systems (e.g. MS SQL) allow only a single null in such cases.

How do I find unique constraints in PostgreSQL?

To find the name of a constraint in PostgreSQL, use the view pg_constraint in the pg_catalog schema. Join the view pg_catalog. pg_constraint with the view pg_class ( JOIN pg_class t ON t. oid = c.


2 Answers

Partial index is what you want:

create unique index some_index on test (id) where active;

As @ThiefMaster states primary index should be removed.

like image 166
kworr Avatar answered Oct 26 '22 02:10

kworr


In this Question’s case it's not needed as explained previously.

But FYI, you can set constraints to 2 or more (non-PrimaryKey) columns with different types. For example:

ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (integer_column, boolean_column);

For more info, see the Postgres doc for Constraints, the "Unique Constraints" section. To quote:

If a unique constraint refers to a group of columns, the columns are listed separated by commas…

This specifies that the combination of values in the indicated columns is unique across the whole table, though any one of the columns need not be (and ordinarily isn't) unique.

Note: A partial index sets an index built over a subset of a table, which has a completely different purpose.

like image 22
Emanuel Canha Avatar answered Oct 26 '22 02:10

Emanuel Canha