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.
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);
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).
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.
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.
Partial index is what you want:
create unique index some_index on test (id) where active;
As @ThiefMaster states primary index should be removed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With