a set of column to be unique key in sql database - sql

How can I make a set of column to be unique key in sql server database?
for example: I have a database that have just one table by columns 1_book 2_page 3_line 4_word i want to search a word in some books and record this information .
where is the problem? if it find a words twice or more in a line it will save the same record to table.it is not important for me how many times a word is repeated in a line. i want if a word to be repeated once or more save the information.
is there any way to say every record should be unique?
searching a record in table before Inserting it to table is not reasonable .isn't it?

Just create a unique constraint for your table: (example for ms sql-server)
ALTER TABLE <yourtablename> ADD CONSTRAINT
UniqueEntries UNIQUE NONCLUSTERED
(
1_book, 2_page, 3_line, 4_word
)
If you do not want to get errors and simply ignore additional adds of the same word in the same line, you can extend the constraint with IGNORE_DUP_KEY = ON
Example:
ALTER TABLE <yourtablename> ADD CONSTRAINT
UniqueEntries UNIQUE NONCLUSTERED
(
1_book, 2_page, 3_line, 4_word
) WITH (IGNORE_DUP_KEY = ON)
Inserts with already existing records will then just be silently ignored.

You mean, you don't know how to create composite keys? Well:
alter table dbo.Words add constraint PK_Words primary key (
1_book, 2_page, 3_line, 4_word
);
And if you don't want key violations while adding data, use merge instead of insert (assuming your SQL Server version is 2008 or later).

Related

How to prevent dupilcate value at table creation

Suppose user name and phone number should be unique at the time of table define without using unique constraint and check constraint in sql server.i don't want to create sp for that.please suggest any otherway to prevent duplicate column in sql server r2 2008. Il
One correct way (and really the best way) is to use a unique constraint. It is unclear whether you want one or two constraints, based on your description. If you don't want a unique constraint, you should explain why not.
That is, if you want the pair to be unique:
alter table add constraint unq_t_username_phonenumber unique (username, phonenumber);
Or you want each one to be unique:
alter table add constraint unq_t_username unique (username);
alter table add constraint unq_t_phonenumber unique (phonenumber);
When you define the table, you can also do one-column unique constraints in-line:
create table . . . (
. . .,
UserName varchar(255) not null unique,
. . .
);
Almost equivalent to a unique constraint is a unique index:
create unique index unq_t_username on t(username);
The difference is that you can name the constraint. This name is handy when a violation occurs, because the constraint name (but not index name) is typically in the message.

SQL: Create new column with default, unique value

I have added a new column, called Ordinal, to a table called Activity. The problem is that I gave it a UNIQUE constraint, set it to allow NULL (though this I won't want in the end.. I just needed to set it to that to get a little farther with the script), and did not give it a default value. I'm now running a RedGate SQL Compare script that was generated by comparing this table to a version of the Activity table that does not have the column. But I'm getting the following error:
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'iwt.Activity' and the index name 'IX_Activity'. The duplicate key value is (1).
So based on my research, it's trying to create a unique key constraint on the Ordinal column, but NULL is not unique. So my next step was to give it a unique value of 1 just to let the script pass. But 1 isn't going to be unique either. So, finally, my question:
Preferably in SQL Server Management Studio, how do I set a column as having a unique default value? Isn't that what I would need to create this constraint?
Thanks.
try this:
NULL will be the first constraint when you create the column.
UNIQUE will be as add constraint, you should add the second constraint.
they can run on this order with no problem (tested):
--first constraint
alter table Table_Name
add Column_Name int null
--second constraint
alter table Table_Name
add constraint Constraint_Name unique (Column_Name)
In my example :
PaymentGatewayHash is column
Cart is a table
--first query
alter table Cart
add PaymentGatewayHash NVARCHAR(20) null
--second query
CREATE UNIQUE INDEX PaymentGatewayHashUnique
ON Cart (PaymentGatewayHash)
WHERE PaymentGatewayHash IS NOT NULL
I just tested that :D

Constraint is key is index is constraint?

in SQL Server Management Studio (SSMS) 2008 R2 Dev on the table (because I cannot ask without it)
--SET ANSI_NULL_DFLT_ON ON
create table B (Id int)
I create unique constraint
ALTER TABLE B
ADD CONSTRAINT IX_B
UNIQUE (ID)
WITH (IGNORE_DUP_KEY = ON)
SSMS shows that I do not have any constraint but have a key + index instead while context options (on right clicking) hint me to create (sorry, script) still constraint.
MAIN QUESTION:
What is a key here?
Why is it needed for this constraint?
Why is unique constraint called by key (and key by unique constraint)?
Sorry, again, why is key called by index? They seem to have the same name (though had I created without explicit name they would have called differently)...
Sorry, again...
COLLATERAL questions:
Which functionality is different between "unique constraint" vs. "unique index"? I searched today for a single difference (wanted to find 10) quite a time and could not find any.
In other words, what's for (why) are concepts (or constructs) "unique constraint" and "unique index" are duplicated in SQL Server?
Bonus question (for those whom this question seemed too simple):
What is the sense in unique index (or in unique constraint) permitting dupes?
insert into B VALUES (1)
insert into B VALUES (1)
insert into B VALUES (1)
Update: Sorry Thanks, guys and ladies (bonus is withdrawn)
Update2: Was not there a difference between "unique index" and "unique constraint" in previous SQL Server (I vaguely recall that one of them did not permit NULL)?
Update3: Really, I was always pissed off (confused) by a "foreign key constraint" is called by "foreign key" while it is not a key and the key, foreign one is in another table, foreign one ... and just found that this is universal confusion to rattle on it. At least, now I memorize that I should remember au contraire.
Update4:
#Damien_The_Unbeliever, thanks,
these are, at least, some hrooks to memorize confusion.
Though, some bewilderments:
Why are these candidates NOT NULL by default?
Initially I really wanted to insert much shorter script:
CREATE TABLE A(A INT UNIQUE);
which produced:
WTF this "candidate" for PRIMARY and KEY has multiple identities syndrome, then?
Is not "UQ_" stand for Unique constraint in naming practices?
Now, scripting of this index UQ__A__3214EC262AA05119 produces nameless... not index ... constraint(?!):
ALTER TABLE [dbo].[A] ADD UNIQUE NONCLUSTERED
(
[ID] ASC
)
WITH
( PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
SORT_IN_TEMPDB = OFF,
IGNORE_DUP_KEY = OFF,
ONLINE = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON)
ON
[PRIMARY]
WTheF - How is unique index is identified as constraint? Where, by what
Scripting of key produces the same! again, constraint...
Why is it nameless? Why is it impossible to script as "modify" but only as "create"?!
This does not make sense!
Now if to execute the produced script, there are 2 dupes,
to execute once more - voila: 3 dupe "candidates"
Note: if to create the unique constraint by separate T-SQL statement with custom/manual name, as I made at the top, then scripting does not produce anonymous DML and, respectively, their execution does not permit multiplication of "candidates"
Strange candidates for primary keys, aren't they? need to visit a shrink (with multiple identities symptoms)?
A UNIQUE constraint is also known as a UNIQUE KEY constraint. Basically, there can be multiple KEYs for a table. One is selected (somewhat arbitrarily) to be the PRIMARY KEY for the table. Other keys are created as UNIQUE KEY constraints.
As an implementation detail, a UNIQUE KEY constraint is implemented by placing a UNIQUE index on the same columns in the table. However, it is possible to create UNIQUE indexes on a table (via CREATE INDEX), without creating a UNIQUE constraint.
UNIQUE constraints are similar to PRIMARY KEYs - they can be the target reference for a FOREIGN KEY constraint. A UNIQUE index, by itself, cannot be so referenced.
In SSMS, PRIMARY KEY, UNIQUE, and FOREIGN KEY constraints will always show up under the "Keys" folder for a table. CHECK and DEFAULT constraints will show up under the "Constraints" folder
This only answers part of your question, as I'm not clear on why management studio displays these objects the way it does.
A unique constraint is part of the (logical) relational model. Essentially if you were drawing out the logical model, a unique constraint would appear on the drawing.
A unique index (like all indexes) is an implementation detail, so is part of the physical model.
SQL Server uses a unique index to implement a unique constraint. There is a logical difference, and I think this shows up in the SQL Server diagramming tool--if you use a unique constraint on a foreign key in what otherwise would be a 1:n relationship, it shows up as a 1:1. This is not true when using a unique index (again, not 100% sure on this).
first off all your table has only 1 value not 3, take a look
create table B (Id int)
ALTER TABLE B
ADD CONSTRAINT IX_B
UNIQUE (ID)
WITH (IGNORE_DUP_KEY = ON)
insert into B VALUES (1)
insert into B VALUES (1)
insert into B VALUES (1)
--Duplicate key was ignored.
--Duplicate key was ignored.
select * from B
One row, right?
This is because you have this WITH (IGNORE_DUP_KEY = ON)
now do this
create table C (Id int)
ALTER TABLE C
ADD CONSTRAINT IX_C
UNIQUE (ID)
insert into C VALUES (1)
insert into C VALUES (1)
The second row won't go into the table now
The way that SQL Server implements constraint is that it creates an index behind it to facilitate fast lookups among other things.
Perhaps you really want a primary key on this table?
create table D (Id int not null primary key)
A unique constraint is implemented internally as an index.
Pretty much the only difference between explicit CREATE INDEX and adding a constraint via ALTER TABLE is the ability to have INCLUDE columns as an explicit index.
SSMS is somewhat confusing in how it presents this. No idea why
Personally, I think IGNORE_DUP_KEY is pointless and have never used it.
Specifies the error response to
duplicate key values in a multiple-row
insert operation on a unique clustered
or unique nonclustered index. The
default is OFF.
ON
A warning message is issued and
only the rows violating the unique
index fail.
OFF
An error message is issued and the
entire INSERT transaction is rolled
back.
The IGNORE_DUP_KEY setting applies
only to insert operations that occur
after the index is created or rebuilt.
The setting has no affect during the
index operation.
Edit:
Found this from me before: Can I set ignore_dup_key on for a primary key?
Generally, IGNORE_DUP_KEY has several answers too

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.

SQL Server 2005 How Create a Unique Constraint?

How do I create a unique constraint on an existing table in SQL Server 2005?
I am looking for both the TSQL and how to do it in the Database Diagram.
The SQL command is:
ALTER TABLE <tablename> ADD CONSTRAINT
<constraintname> UNIQUE NONCLUSTERED
(
<columnname>
)
See the full syntax here.
If you want to do it from a Database Diagram:
right-click on the table and select 'Indexes/Keys'
click the Add button to add a new index
enter the necessary info in the Properties on the right hand side:
the columns you want (click the ellipsis button to select)
set Is Unique to Yes
give it an appropriate name
In SQL Server Management Studio Express:
Right-click table, choose Modify or Design(For Later Versions)
Right-click field, choose Indexes/Keys...
Click Add
For Columns, select the field name you want to be unique.
For Type, choose Unique Key.
Click Close, Save the table.
ALTER TABLE [TableName] ADD CONSTRAINT [constraintName] UNIQUE ([columns])
Warning: Only one null row can be in the column you've set to be unique.
You can do this with a filtered index in SQL 2008:
CREATE UNIQUE NONCLUSTERED INDEX idx_col1
ON dbo.MyTable(col1)
WHERE col1 IS NOT NULL;
See Field value must be unique unless it is NULL for a range of answers.
ALTER TABLE dbo.<tablename> ADD CONSTRAINT
<namingconventionconstraint> UNIQUE NONCLUSTERED
(
<columnname>
) ON [PRIMARY]
I also found you can do this via, the database diagrams.
By right clicking the table and selecting Indexes/Keys...
Click the 'Add' button, and change the columns to the column(s) you wish make unique.
Change Is Unique to Yes.
Click close and save the diagram, and it will add it to the table.
You are looking for something like the following
ALTER TABLE dbo.doc_exz
ADD CONSTRAINT col_b_def
UNIQUE column_b
MSDN Docs
To create a UNIQUE constraint on one or multiple columns when the table is already created, use the following SQL:
ALTER TABLE TableName ADd UNIQUE (ColumnName1,ColumnName2, ColumnName3, ...)
To allow naming of a UNIQUE constraint for above query
ALTER TABLE TableName ADD CONSTRAINT un_constaint_name UNIQUE (ColumnName1,ColumnName2, ColumnName3, ...)
The query supported by MySQL / SQL Server / Oracle / MS Access.
In the management studio diagram choose the table, right click to add new column if desired, right-click on the column and choose "Check Constraints", there you can add one.
In some situations, it could be desirable to ensure the Unique key does not exists before create it. In such cases, the script below might help:
IF Exists(SELECT * FROM sys.indexes WHERE name Like '<index_name>')
ALTER TABLE dbo.<target_table_name> DROP CONSTRAINT <index_name>
GO
ALTER TABLE dbo.<target_table_name> ADD CONSTRAINT <index_name> UNIQUE NONCLUSTERED (<col_1>, <col_2>, ..., <col_n>)
GO