Postgres add unique constraint - sql

I need to add a constraint to a table x which has many to one relation to other table. So the table x has field other_table_id.
There is other column in table x called primary which is boolean type.
I want to make sure that there is none or only one primary=true per one other_table_id.
Multiple rows can have other_table_id equals some same value and primary=false but only one true per other_table_id.
How do I create this constraint?

You need a partial unique index for that:
create unique index idx_unique_other
on table_x (other_table_id)
where primary;
This will only index rows where the value of primary column is true. And for those, the other_table_id has to be unique.

Related

Unique constrain for values combination in Postgresql

is it possible to create unique constrain in Postgresql, that would take into account column values and work with some value, but not with another?
I have table, where items have "code" that must be unique, but records aren't deleted from table, just marked as deleted (special boolean field "deleted"). I could create unique(code, deleted) to enforce uniqueness, it works if I don't mark 2 rows as deleted with same "code". If I would try to "delete" second row, it will alert that 2 rows will have same unique values and doesn't allow.
What I would like to have, is check unique field "code" for every row, that "deleted" is false.
You can't do this with a consraint. However, in Postgres, a partial unique index would do exactly what you want:
create unique index myindex on mytable(code) where (deleted = false);
You can also phrase this as:
create unique index myindex on mytable(code) where (not deleted);

SQL Server add check constraint for ordered pair with specific value for one of the columns

Consider the following table
I want to add constraint which says "The ID numbers must be unique". This means that I cannot have the same Value when the Type is ID_NUMBER, but I can have the same value with another Type (e.g USERNAME).
How can achieve this ? I was thinking about some kind of check constraint on the two columns but I don't know how to provide "ID_NUMBER" for the value of one of the columns in the constraint.
You can create a filtered unique index:
create unique index unq_table_value on table(value) where field = 'ID_NUMBER';

How to add not null unique column to existing table

Is there any way to simply add not null unique column to existing table. Something like default = 1++ ? Or simply add unique column?
I tried to add column and then put unique contrain but MS SQL says that:
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name (...) The duplicate key value is ( < NULL > ).
Any way to simply add column to existing working table with unique constrain? Should MS SQL really think that null IS a value?
Add not null column with some default.
Update column to be a sequential integers (see row_number() function)
Add UNIQUE constraint or UNIQUE index over new column
You can add IDENTITY column to a table (but from question it is not clear if you need it or not).
IDENTITY is all you need:
ALTER TABLE TestTable
ADD ID INT IDENTITY(1, 1)
If you want an autonumber, you can add an identity.
If you need to populate the values yourself, you add the column allowing nulls, update the values, check to make sure they are unique and that there are no nulls, then add the unique constraint and trhe not null property. It is best to do this during a maintenance window when no one else would be changing data in that table.

Is it necessary to have separate column for primary key in table?

I have column having name id in my table. id is the primary key in table. I want to know that is it necessary to have separate column for id as it is primary key in my table.
Not necessary to have a separate column, you could have an existing column as primary key if it can identify each record uniquely..
Any field or combination of fields can be a primary key if:
The values in those fields are always non-null.
The records with values in those fields are unique.
Those fields are immutable. That is, you won't change the values of those fields
after the record is created.
It's always better to keep things simple. If you already have a column that identifies the record it's just fine - don't add a new one.
There is also something called composite primary keys. You can use it if a combination of 2 or more columns always creates a unique sequence. Than you don't really need the 'Id' column. The truth though is some frameworks don't like this approach.
In your case the column you already have should be sufficient.
The PRIMARY KEY constraint uniquely identifies each record in a database table and if your table already contain that column then u don't need to add another column.

How to create a unique index on a NULL column?

I am using SQL Server 2005. I want to constrain the values in a column to be unique, while allowing NULLS.
My current solution involves a unique index on a view like so:
CREATE VIEW vw_unq WITH SCHEMABINDING AS
SELECT Column1
FROM MyTable
WHERE Column1 IS NOT NULL
CREATE UNIQUE CLUSTERED INDEX unq_idx ON vw_unq (Column1)
Any better ideas?
Using SQL Server 2008, you can create a filtered index.
CREATE UNIQUE INDEX AK_MyTable_Column1 ON MyTable (Column1) WHERE Column1 IS NOT NULL
Another option is a trigger to check uniqueness, but this could affect performance.
The calculated column trick is widely known as a "nullbuster"; my notes credit Steve Kass:
CREATE TABLE dupNulls (
pk int identity(1,1) primary key,
X int NULL,
nullbuster as (case when X is null then pk else 0 end),
CONSTRAINT dupNulls_uqX UNIQUE (X,nullbuster)
)
Pretty sure you can't do that, as it violates the purpose of uniques.
However, this person seems to have a decent work around:
http://sqlservercodebook.blogspot.com/2008/04/multiple-null-values-in-unique-index-in.html
It is possible to use filter predicates to specify which rows to include in the index.
From the documentation:
WHERE <filter_predicate> Creates a filtered index by specifying which
rows to include in the index. The filtered index must be a
nonclustered index on a table. Creates filtered statistics for the
data rows in the filtered index.
Example:
CREATE TABLE Table1 (
NullableCol int NULL
)
CREATE UNIQUE INDEX IX_Table1 ON Table1 (NullableCol) WHERE NullableCol IS NOT NULL;
Strictly speaking, a unique nullable column (or set of columns) can be NULL (or a record of NULLs) only once, since having the same value (and this includes NULL) more than once obviously violates the unique constraint.
However, that doesn't mean the concept of "unique nullable columns" is valid; to actually implement it in any relational database we just have to bear in mind that this kind of databases are meant to be normalized to properly work, and normalization usually involves the addition of several (non-entity) extra tables to establish relationships between the entities.
Let's work a basic example considering only one "unique nullable column", it's easy to expand it to more such columns.
Suppose we the information represented by a table like this:
create table the_entity_incorrect
(
id integer,
uniqnull integer null, /* we want this to be "unique and nullable" */
primary key (id)
);
We can do it by putting uniqnull apart and adding a second table to establish a relationship between uniqnull values and the_entity (rather than having uniqnull "inside" the_entity):
create table the_entity
(
id integer,
primary key(id)
);
create table the_relation
(
the_entity_id integer not null,
uniqnull integer not null,
unique(the_entity_id),
unique(uniqnull),
/* primary key can be both or either of the_entity_id or uniqnull */
primary key (the_entity_id, uniqnull),
foreign key (the_entity_id) references the_entity(id)
);
To associate a value of uniqnull to a row in the_entity we need to also add a row in the_relation.
For rows in the_entity were no uniqnull values are associated (i.e. for the ones we would put NULL in the_entity_incorrect) we simply do not add a row in the_relation.
Note that values for uniqnull will be unique for all the_relation, and also notice that for each value in the_entity there can be at most one value in the_relation, since the primary and foreign keys on it enforce this.
Then, if a value of 5 for uniqnull is to be associated with an the_entity id of 3, we need to:
start transaction;
insert into the_entity (id) values (3);
insert into the_relation (the_entity_id, uniqnull) values (3, 5);
commit;
And, if an id value of 10 for the_entity has no uniqnull counterpart, we only do:
start transaction;
insert into the_entity (id) values (10);
commit;
To denormalize this information and obtain the data a table like the_entity_incorrect would hold, we need to:
select
id, uniqnull
from
the_entity left outer join the_relation
on
the_entity.id = the_relation.the_entity_id
;
The "left outer join" operator ensures all rows from the_entity will appear in the result, putting NULL in the uniqnull column when no matching columns are present in the_relation.
Remember, any effort spent for some days (or weeks or months) in designing a well normalized database (and the corresponding denormalizing views and procedures) will save you years (or decades) of pain and wasted resources.