how to enforce multiple unique fields in database table - sql

i have a table called Cars and the primary key of the table is 'id'. I also have a field called 'name'. I would like to make sure no one enters the same name twice even though it wont break my db integrity.
what is the best way of doing this?

create unique index cars_unique_name on cars(name)

Just create a UNIQUE index on the name field. In SQL it would be something like this:
CREATE UNIQUE INDEX IX_Cars_name
ON Cars(name);
Another possibility is to create a unique constraint, like this:
ALTER TABLE Cars
ADD CONSTRAINT Uqc_Cars_name
UNIQUE (name)
Both will do essentially the same thing.

you can specify the unique index constraint both in CREATE TABLE command or ALTER TABLE command.
Its like
CREATE TABLE CARS (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) UNIQUE KEY
);
or just create the above table
CREATE TABLE CARS (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);
and later add the unqiue key index using alter table

As mentioned, you will probably want a unique index, but it is also possible to use a unique constraint, with no index which might be desirable in some situations...
CREATE TABLE cars
(
ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED,
NAME NVARCHAR(100) UNIQUE NOT NULL
)
or
ALTER TABLE cars
ADD CONSTRAINT UniqueConstraintName UNIQUE (name)

Related

Can I add an autoincrementing primary key to a SQLite table that already exists?

I have this table in SQLite:
CREATE TABLE countries (
name VARCHAR(255),
population INT
);
I now want to add a new auto-incrementing, primary key column.
I basically want to do this:
ALTER TABLE countries ADD COLUMN id INTEGER PRIMARY KEY AUTOINCREMENT;
But when running this query, I always get this error:
Query 1 ERROR: Cannot add a PRIMARY KEY column
Does anyone know whether that's even possible with SQLite?

Condition for some column in foreign key

There is table A with columns (Id, BId). BId is foreign key to table B. B has columns (Id, Type).
CREATE TABLE [A] (
[Id] INT IDENTITY CONSTRAINT [PK_A_Id] PRIMARY KEY,
[BId] INT NOT NULL CONSTRAINT [FK_A_B] REFERENCES [B](Id)
)
GO
CREATE TABLE [B] (
[Id] INT IDENTITY CONSTRAINT [PK_B_Id] PRIMARY KEY,
[Type] INT NOT NULL
)
GO
So, it is very simple scheme, but I want to add condition for foreign keys like "type should be 0". It should be something like
CONSTRAINT [FK_A_B] REFERENCES [B](Id) WHERE [B].[Type] = 0
How to use UNIQUE keyword or smth else correctly to realize it?
What you are trying to achieve is not a task for FOREIGN KEY. In FK you can't specify additional conditions on a target table. If you have such need, usually it means that your DB is not normalized. It looks like table [B] stores several data entities in one table, and Type column determines what entity it is. If you broke normalization rules, declarative integrity means like FK don't work for you. From now on you have to control integrity on your own. You can do this in application logic or create triggers (procedural integrity). In any case there will be no foreign key constraint in DB.
It would be nice if this could be done using a filtered unique index. But, SQL Server doesn't allow that. So here is another idea:
Start by defining a (redundant) unique constraint on:
CREATE TABLE [B] (
[Id] INT IDENTITY CONSTRAINT [PK_B_Id] PRIMARY KEY,
[Type] INT NOT NULL,
UNIQUE (ID, Type)
)
GO
Now, I don't think you can define the constraint as:
CONSTRAINT [FK_A_B] (ID, 0) REFERENCES [B](Id, Type)
But, I think you can trick it by doing:
_Type as 0,
CONSTRAINT [FK_A_B] (ID, _Type) REFERENCES [B](Id, Type)
That is, add a computed column and use that for the constraint.

Is my query correct when I set primary key for 3 columns in a table?

In my case, I have only 1 candidate may go with 1 job at the time so they are must be 2 primary key.
Then, a column is as JobApplicationId use for the table CandidateDetail as a foreign key.
Is that correct when I decide to set these 3 columns above as primary key or there are other ways to address my problem here?
CREATE TABLE Candidate(
CandidateId int identity primary key,
FullName nvarchar(50)
)
CREATE TABLE Job(
JobId int identity primary key,
JobTitle nvarchar(50)
)
CREATE TABLE JobApplication(
JobApplicationId int identity,
JobId int,
CandidateId int,
CreatedDate datetime,
primary key(JobApplicationId, JobId, CandidateId)
)
CREATE TABLE CandidateDetail(
CandidateDetailId int identity primary key,
JobApplicationId int,
[Description] nvarchar(300)
)
ALTER TABLE JobApplication ADD CONSTRAINT fk_JobApplication_Job FOREIGN KEY (JobId) REFERENCES Job(JobId)
ALTER TABLE JobApplication ADD CONSTRAINT fk_JobApplication_Candidate FOREIGN KEY (CandidateId) REFERENCES Candidate(CandidateId)
ALTER TABLE CandidateDetail ADD CONSTRAINT fk_CandidateDetail_JobApplication FOREIGN KEY (JobApplicationId) REFERENCES JobApplication(JobApplicationId)
Instead of a primary key with three columns you could just have JobApplicationId as the primary key and a unique constraint on JobId, CandidateId.
Otherwise, two rows with JobApplicationId=1, JobId=1, CandidateId=1 and JobApplicationId=2, JobId=1, CandidateId=1 would still be valid in terms of your current primary key approach, but would be invalid in terms of the business case.
From both a performance and usability perspective, a compound primary key can be a hassle and can create performance issues. Personally, I would choose JobApplicationId as the primary key (because this is an identity column and will be unique for each record). Then, if you need to constrain the table so that JobId and CandidateId are always unique (not allowing more than 1 record for any given candidate and the job they've applied for) then I would use a compound Unique Constraint.
However, I would suggest that you evaluate those requirements more closely because what if a candidate applies for the same position in a different time frame? It might stand to reason that having the same candidate applied to the same job more than once in that table might be valid data.

How to create composite primary key in SQL Server 2008

I want to create tables in SQL Server 2008, but I don't know how to create composite primary key. How can I achieve this?
create table my_table (
column_a integer not null,
column_b integer not null,
column_c varchar(50),
primary key (column_a, column_b)
);
CREATE TABLE UserGroup
(
[User_Id] INT NOT NULL,
[Group_Id] INT NOT NULL
CONSTRAINT PK_UserGroup PRIMARY KEY NONCLUSTERED ([User_Id], [Group_Id])
)
Via Enterprise Manager (SSMS)...
Right Click on the Table you wish to create the composite key on and select Design.
Highlight the columns you wish to form as a composite key
Right Click over those columns and Set Primary Key
To see the SQL you can then right click on the Table > Script Table As > Create To
I know I'm late to this party, but for an existing table, try:
ALTER table TABLE_NAME
ADD CONSTRAINT [name of your PK, e.g. PK_TableName] PRIMARY KEY CLUSTERED (column1, column2, etc.)
For MSSQL Server 2012
CREATE TABLE usrgroup(
usr_id int FOREIGN KEY REFERENCES users(id),
grp_id int FOREIGN KEY REFERENCES groups(id),
PRIMARY KEY (usr_id, grp_id)
)
UPDATE
I should add !
If you want to add foreign / primary keys altering, firstly you should create the keys with constraints or you can not make changes. Like this below:
CREATE TABLE usrgroup(
usr_id int,
grp_id int,
CONSTRAINT FK_usrgroup_usrid FOREIGN KEY (usr_id) REFERENCES users(id),
CONSTRAINT FK_usrgroup_groupid FOREIGN KEY (grp_id) REFERENCES groups(id),
CONSTRAINT PK_usrgroup PRIMARY KEY (usr_id,grp_id)
)
Actually last way is healthier and serial. You can look the FK/PK Constraint names (dbo.dbname > Keys > ..) but if you do not use a constraint, MSSQL auto-creates random FK/PK names. You will need to look at every change (alter table) you need.
I recommend that you set a standard for yourself; the constraint should be defined according to the your standard. You will not have to memorize and you will not have to think too long. In short, you work faster.
First create the database and table, manually adding the columns. In which column to be primary key. You should right click this column and set primary key and set the seed value of the primary key.
To create a composite unique key on table
ALTER TABLE [TableName] ADD UNIQUE ([Column1], [Column2], [column3]);
CREATE TABLE UserGroup
(
[User_Id] INT Foreign Key,
[Group_Id] INT foreign key,
PRIMARY KEY ([User_Id], [Group_Id])
)

How to add composite primary key to table

create table d(id numeric(1), code varchar(2))
After I create the above table how can I add a composite primary key on both fields and also a foreign key?
In Oracle, you could do this:
create table D (
ID numeric(1),
CODE varchar(2),
constraint PK_D primary key (ID, CODE)
);
alter table d add constraint pkc_Name primary key (id, code)
should do it. There's lots of options to a basic primary key/index depending on what DB your working with.
The ALTER TABLE statement presented by Chris should work, but first you need to declare the columns NOT NULL. All parts of a primary key need to be NOT NULL.
You don't need to create the table first and then add the keys in subsequent steps. You can add both primary key and foreign key while creating the table:
This example assumes the existence of a table (Codes) that we would want to reference with our foreign key.
CREATE TABLE d (
id [numeric](1),
code [varchar](2),
PRIMARY KEY (id, code),
CONSTRAINT fk_d_codes FOREIGN KEY (code) REFERENCES Codes (code)
)
If you don't have a table that we can reference, add one like this so that the example will work:
CREATE TABLE Codes (
Code [varchar](2) PRIMARY KEY
)
NOTE: you must have a table to reference before creating the foreign key.
If using Sql Server Management Studio Designer just select both rows (Shift+Click) and Set Primary Key.