SQL Server CHECK Constraint - Ensure no duplicates on text - sql

Need to add some sort of constraint on my table column. I need to make sure that the user does not enter, manually or otherwise, the same text in more than one row of the table. How can I achieve this?

You'll want to use some type of unique constraint or, of course, the primary key would work as well. For example:
ALTER TABLE MyTable ADD CONSTRAINT UK_MyUniqueConstraint UNIQUE (MyColumn)
There are other methods of creating this discussed on SE as well.

Related

Query to Alter Primary Key to any column with keyword

I have a database with several tables that I am looking to add primary keys to any column with the keyword "KEY" in its name. The first problem that doesn't seem fixable is to run a query against all tables rather than one by one... Secondly I don't see how I can Add Primary key or even drop constraints on wildcard column searches.
For those of you who are visual, this is what I am trying to achieve:
ALTER TABLE *
ADD PRIMARY KEY (%KEY%);
Keeping in mind SOME tables already have Primary Keys attached, so I may need to Drop Constraints on all first then re-constrain them. If even possible?
If you want to define existing autonumber fields as primary key, consider:
ALTER TABLE tablename ADD CONSTRAINT fieldname PRIMARY KEY(fieldname)
However, field cannot already be set with an index and table cannot already have a primary key. Again, use ALTER TABLE to remove index.
ALTER TABLE tablename DROP CONSTRAINT indexname
Will have to run this SQL for each table that must be modified. If this is a one-time only requirement (why would it not be?), probably just as fast to open each table and manually modify design.
MS documentation https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/alter-table-statement-microsoft-access-sql
The alternative is VBA using TableDefs to modify table structure. Search web for examples.

PostgreSQL - Add CONSTRAINT UNIQUE and do not validate exisiting data

I have a small problem with adding new CONSTRAINT to my table.
I want to add a UNIQUE CONSTRAINT and do not validate existing data in my table.
I have some duplicates in existing data and I want to leave it like it is.
I wrote a query:
ALTER TABLE tbl1
ADD CONSTRAINT unique_const UNIQUE (fld1, fld2) NOT VALID;
But it's not working, I got an error:
UNIQUE constraints cannot be marked NOT VALID
I also tried removing all TRIGGERS:
ALTER TABLE tbl1 DISABLE TRIGGER all;
ALTER TABLE tbl1 ADD CONSTRAINT unique_const UNIQUE (fld1, fld2);
ALTER TABLE tbl1 ENABLE TRIGGER all;
But it also does not work.
Does anyone know how to add a UNIQUE CONSTRAINT without validating existing rows?
According to the documentation of PostgreSQL 9.6, unfortunately the NOT VALID option is currently only allowed with foreign key and CHECK constraints.
This StackOverflow thread here might be related and provide ideas/basic approaches for an alternative solution, although it's from 2014.
If you can specifically identify those lines which should be ignored for the constraint, you could add a partial unique index:
CREATE UNIQUE INDEX ON table (columns) WHERE some_condition;
If you don't have an existing direct condition, you may need to add a column to the table to identify those lines that should be ignored (with an appropriate default so that new lines are counted).
Not sure if there's an equivalent ALTER TABLE syntax.

Multiple foreign keys and multiple constrains

Let's assume I have a table called boxes with the box_id attribute as the PK.
There are two other tables. The first one is red_boxes and the second blue_boxes.
I have added a constraint to the red_boxes table
ALTER TABLE red_boxes
ADD CONSTRAINT fk_box_id
FOREIGN KEY (box_id)
REFERENCES boxes (box_id);
Now, I would like to add a constraint to the blue_boxes table. The SQL structure would look like the following, if I did not add the constraint already to the the red_boxes. The obvious way to fix this is to name a new constraint differently e.g. fk_box_id2, but is this is a good way? Am I supposed to somehow re-use the previous constraint, or this is not possible, why?
ALTER TABLE blue_boxes
ADD CONSTRAINT fk_box_id
FOREIGN KEY (box_id)
REFERENCES boxes (box_id)
Each constraint is separate and requires a unique name. My recommendation is to use the source and destination table names, for example fk_red_boxes_boxes and fk_blue_boxes_boxes. This way you can easily identify where they come from and where they go to.
If you have underscores in your table names, you might want to come up with a modified convention that you can easily understand at a glance. For example, a double underscore: fk__blue_boxes__boxes and fk__red_boxes__boxes.

Where to state a foreign key when creating a table?

I would like to design a table named arguments whose an attribute name is linked to another attribute name in a table called names.
I see two ways to express it in SQL:
by creating a constraint on the table:
CREATE TABLE names ( name text UNIQUE,
short text UNIQUE,
comment text);
CREATE TABLE arguments ( name text UNIQUE,
comment text,
FOREIGN KEY (name) REFERENCES names (name));
by qualifying the attribute on-the-fly:
CREATE TABLE names ( name text UNIQUE,
short text UNIQUE,
comment text);
CREATE TABLE arguments ( name text UNIQUE REFERENCES names (name),
comment text);
I would like to know:
if one of the two is commonly known as better than the other, and
if it can have consequences that I should be aware of.
Thank you for your help.
These are just different syntax for the same end result.
Either is appropriate, but the former is a more common style in my experience. This may simply be to allow the human mind to more easily digest all the information. First describe the data, second describe how it relates to the rest of the world.
One comment I would make though, is that is more common to have IDs as unique identifiers and references. This allows you to change the Value in the Name field without changing it's Identity and breaking Referential Integrity. There are databases that can cascade such changes and update all occurrences of the Name, but in general it's considered cleaner to have Identifiers that are Separate from the Data.
While the first option is known as out-of-line constraint declaration and the second option is in-line, both of them are functionally same.
What would be better is to assign a name to the foreign key constraint. If you have a name, you can selectively enable and disable the constraint if required.
Create table
CREATE TABLE arguments
(
name text UNIQUE,
comment text,
constraint arguments_fk FOREIGN KEY (name) REFERENCES names (name)
);
Disable constraint
ALTER TABLE arguments NOCHECK CONSTRAINT arguments_fk;
Enable constraint
ALTER TABLE arguments CHECK CONSTRAINT arguments_fk;
This is for SQL Server. Oracle has equivalent commands.
Use a foreign key. If you later find you have a performance problem (a measurable problem), then you can change it up to be different.
Keep things simple at first and get the product into the users' hands as fast as possible. Don't optimize things that you can't prove need it.

Alter composite key to include newly added column in sql server 2005

I have a table GB_Assignor_Assignee. I have a primary key which includes this combination(StateCode, CountyID, Doc_Type_Group_Code). Now i have to add a new column Doc_Type_Code. I added it by altering table. I want to include this new column inside this primary key.So my combination will be(StateCode, CountyID, Doc_Type_Group_Code,Doc_Type_Code).
How can i alter this primary key to add new column. I donot want to drop it and then recreate it. Please suggest.
If you want to change the primary key to include a new column, you have to drop and recreate it - there's no other way. You cannot add a column to an existing primary key after it's been created.
The question is: wouldn't you be better off creating a new artificial ID (of type INT) as your PK? You wouldn't have to change it if yet another column comes along, referencing the table will be MUCH easier (JOIN on just a single INT instead of five or six columns)......
You have to drop and recreate your PK.
This involves dropping any foreign keys that reference it. This should be obvious in any case as the foreign keys would also have to change to reflect the new column. (Hopefully not many in the case of composite PKs).
Drop the PK itself.
Create the new PK with the additional column.
Recreate all foreign keys.
The easiest way to do this is to make the change in SQL Server's table designer, and ask it to generate the change script for you.