UNIQUE constraint combining multiple columns with a condition - sql

I have a table in Oracle 11g such as with below columns.
COL1_STATUS
COL2_ID
COL3_TYPE
COL4_DATE
I want to create a UNIQUE constraint combining all 4 columns but only when COL1_STATUS = 10
How can I do that? Table is already created so I am looking for only ALTER command.
Also, I have searched and found similar question where it is suggested to use unique index but I want to achieve this by constraint.
Conditional unique constraint with multiple fields in oracle db
Thanks in advance.

A unique index and a constraint are essentially the same thing. A unique constraint is implement using a unique index. So this really should do what you want:
create unique index idx_table_4 on
table(case when status = 10 then id end,
case when status = 10 then type end,
case when status = 10 then date end);
In fact, this is how the documentation recommends implementing a unique constraint:
When you specify a unique constraint on one or more columns, Oracle
implicitly creates an index on the unique key. If you are defining
uniqueness for purposes of query performance, then Oracle recommends
that you instead create the unique index explicitly using a CREATE
UNIQUE INDEX statement. You can also use the CREATE UNIQUE INDEX
statement to create a unique function-based index that defines a
conditional unique constraint. See "Using a Function-based Index to
Define Conditional Uniqueness: Example" for more information.

Related

do not allow duplicates

I am importing data from an access table to SQL. I have a primary key is SQL "quoteID" which obviously doesn't allow duplicates but I'm looking to add that requirement to another field.
Can't seem to find where to set that? perhaps it has to do with the field type??
You can require that a column be unique using a unique constraint or unique index:
alter table t add constraint unq_t_col unique (col);
or:
create unique index unq_t_col on t(col);
Make the field a primary key of the table. Or put an index on that field that enforces unique values.

PostgreSQL: unique constraint or unique index

Should I create unique index if a column contains unique constraint and I want to fast search by this column?
For example I have a table users with column login that should be unique. I need fast search user by the login column.
Which is the best way to do it:
create a unique constraint (it creates internal unique index - is it used in select queries with WHERE login = 'something'?)
create a unique index
create a unique index and unique constraint (index duplicates internal index?)
Second case is unique login on not locked users (column locked = false). Postgres does not support partial conditions. Should I create a unique conditional and a partial index or is only a partial index enough?
And one more question: should I create new index for a column with a foreign key? For example: users.employee_id relates to employees.id, should I create an index on employee column for optimized query SELECT * FROM users WHERE employee_id = ....? When are internal indexes used by the optimization engine and when not?
I have a table 'users' with column login that should be unique
If this is the case you need a unique constraint. Unique constraints are enforced (behind the scenes) by unique indexes.
Conceptually:
The unique constraint defines the uniqueness.
The unique index implements the unique constraint.
The unique index provides speedy searches since it allows operations such as Index Range Scan and Index Seeks.
Is it used in select queries with WHERE login = 'something'?
Yes, it is.
Second case is unique login on not locked users (column locked = false).
If this is the case a unique constraint won't work. Maybe a trigger on insert could help here.
should I create new index for column with foreign key?
No, it's not needed (at least in the current version 10 and perhaps the later versions), s. documentation:
PostgreSQL automatically creates a unique index when a unique constraint or primary key is defined for a table. [...] There's no need to manually create indexes on unique columns; doing so would just duplicate the automatically-created index.

Unique Constraint in SQL with Multiple NULL Values

I recently read about a way to ensure unique values in a column in SQL while allowing multiple NULLS.
This was done using filtered indexes:
CREATE UNIQUE INDEX indexName ON tableName(columns) INCLUDE includeColumns
WHERE columnName IS NOT NULL
Could someone explains how this actually works? Is the UNIQUE constraint created on the column or not ?
To answer your first question: When the index is filtered, anything that doesn't fix the criteria in the where clause is simply left out of the index.
If the index is unique, the uniqueness is enforced only on the data that fits the criteria in the where clause.
To answer your second question: In Sql server unique constraints are implemented by creating unique indexes under the hood, so there really is not much difference between them. In any case the uniqueness is enforced on an index and not directly on the table column.

Oracle Unique Indexes

I was creating a new table today in 10g when I noticed an interesting behavior. Here is an example of what I did:
CREATE TABLE test_table ( field_1 INTEGER PRIMARY KEY );
Oracle will by default, create a non-null unique index for the primary key. I double checked this. After a quick check, I find a unique index name SYS_C0065645. Everything is working as expected so far. Now I did this:
CREATE TABLE test_table ( field_1 INTEGER,
CONSTRAINT pk_test_table PRIMARY KEY (field_1) USING INDEX (CREATE INDEX idx_test_table_00 ON test_table (field_1)));
After describing my newly created index idx_test_table_00, I see that it is non-unique. I tried to insert duplicate data into the table and was stopped by the primary key constraint, proving that the functionality has not been affected. It seems strange to me that Oracle would allow a non-unique index to be used for a primary key constraint. Why is this allowed?
There is actually no structural difference between a unique index and a non-unique index, Oracle can use either for the PK constraint. One advantage of allowing a PK definition like this is that you can disable or defer the constraint for data loading - this isn't possible with a unique index, so one could argue that this implementation is more flexible.
Why not allow it? I love that Oracle gives you lots of options and flexibility.
Maybe you can create one index and use it for two purposes:
validate the PK
help a query perform better
Oracle will by default create a non-null unique index
Oh, and the index has nothing to do with the not null aspect.
see this excellent article about non-unique indexes policing primary keys by Richard Foote. Richard shows that you will take a performance hit when using a non-unique index.
In other words: don't use non-unique indexes to police a primary key constraint unless you really need the constraint to be deferrable.

Does making a column unique force an index to be created?

In SQL Server 2005+ (I use both), does adding the UNIQUE constraint to a column automatically create an index, or should I still CREATE INDEX?
See this MSDN article:
The Database Engine automatically
creates a UNIQUE index to enforce the
uniqueness requirement of the UNIQUE
constraint.
If you do create an index, you'll end up with two indexes, as this example demonstrates:
create table TestTable (id int)
alter table TestTable add constraint unique_id unique (id)
create unique index ix_TestTable_id on TestTable (id)
select * from sys.indexes where [object_id] = object_id('TestTable')
This will display two unique indexes on TestTable; and the HEAP that represents the table itself.
Yes, it does.
In fact, you can even create a CLUSTERED UNIQUE CONSTRAINT:
ALTER TABLE mytable ADD CONSTRAINT UX_mytable_col1 UNIQUE CLUSTERED (col1)
, which will make the table to be clustered on col1.
Almost all databases create an index for UNIQUE CONSTRAINT, otherwise it would be very hard to maintain it.
Oracle doesn't even distinguish between UNIQUE CONSTRAINT and UNIQUE INDEX: one command is just a synonym for another.
The only difference in Oracle is that a UNIQUE INDEX should have a user-supplied name, while a UNIQUE CONSTRAINT may be created with a system-generated name:
ALTER TABLE mytable MODIFY col1 UNIQUE
This will create an index called SYS_CXXXXXX.
An index is created when you add a unique constraint:
Reference -- see the second paragraph.
When a UNIQUE constraint is added to
an existing column or columns in the
table, by default, the Database Engine
examines the existing data in the
columns to make sure all values are
unique. If a UNIQUE constraint is
added to a column that has duplicated
values, the Database Engine returns an
error and does not add the constraint.
The Database Engine automatically
creates a UNIQUE index to enforce the
uniqueness requirement of the UNIQUE
constraint. Therefore, if an attempt
to insert a duplicate row is made, the
Database Engine returns an error
message that states the UNIQUE
constraint has been violated and does
not add the row to the table. Unless a
clustered index is explicitly
specified, a unique, nonclustered
index is created by default to enforce
the UNIQUE constraint.