Foreign key in SQL Server - which style to use? - sql

In my database, I have the following code
CREATE TABLE [Users]
(
userID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Username VARCHAR(255),
Password VARCHAR(255)
);
CREATE TABLE [Image]
(
ImageID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Imagename VARCHAR,
userID INT,
FOREIGN KEY(userID) REFERENCES Users (userID)
);
However, here on stackOverflow and multiple other sites, people suggest writing it like this:
CREATE TABLE [Users]
(
userID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Username VARCHAR(255),
Password VARCHAR(255)
);
CREATE TABLE [Image]
(
ImageID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Imagename VARCHAR,
userID INT,
CONSTRAINT fk_Users
FOREIGN KEY(userID) REFERENCES Users (userID)
);
I've tried executing both statements, and it seems to do the same..
What am I missing, what's the trick when writing CONSTRAINT fk_Users?

Writing constraint allows you to name the constraint.
In general, you notice this when the constraint is violated. If you have an opportunity to name the constraint, the error message will make more sense.
For instance, this:
The INSERT statement conflicted with the FOREIGN KEY constraint
"fk_image_userId". The conflict occurred in database "rextester",
table "dbo.Users", column 'userID'.
The statement has been terminated.
is clearer than this:
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK__Image__userID__09211CD4". The conflict occurred in database
"rextester", table "dbo.Users", column 'userID'.
The statement has been terminated.
In addition, the constraint name is used in the alter table when you drop or disable the constraint, so having a reasonably named constraint makes that easier.

Related

Referenced table not found in the data dictionary mariadb

so I have written this Mariadb code as the solution for an assignment and am running it on HeidiSQL. It should work in theory however I am getting the error message SQL Error (1005): Can't create table bestellung.arbeitetin (errno: 150 "Foreign key constraint is incorrectly formed"). Upon using show warning, the program elaborates that "referenced table bestellung.arbeitetin not found in the data dictionary". I am wondering, is there something wrong with the code?
Datum date not NULL,
Abholtermin DATE,
Kostenstelle int not NULL,
Abteilung char(5) not NULL,
Mitarbeiter int not NULL,
Telefon int not NULL,
primary key (Bestellnummer)
);
create table enthaelt (
FK_Bestellnummer int not NULL,
FK_Artikelnummer char(10) not NULL,
Menge int not NULL,
unique key (FK_Bestellnummer, FK_Artikelnummer)
);
alter table enthaelt ADD
constraint FK_ArtikelNr
foreign key (FK_Artikelnummer)
references Artikel (Artikelnummer);
alter table enthaelt ADD
constraint FK_BestellNr
foreign key (FK_Bestellnummer)
references Bestellung (Bestellnummer);
create table arbeitetin
(
FK_PersNr int not NULL,
FK_ProjektNr int not NULL,
unique key(FK_PersNr, FK_ProjektNr)
);
alter table arbeitetin ADD
constraint FK_ARBEITETIN_MITARBEITER1
FOREIGN KEY (FK_PersNr)
REFERENCES Mitarbeiter (PersNr);
alter table arbeitetin ADD
constraint FK_ARBEITETIN_PROJEKT
foreign key (FK_ProjektNr)
references Projekt (ProjektNr);
alter table Mitarbeiter ADD
constraint FK_MITARBEITER_ABTEILUNG
foreign key (FK_Abkuerzung)
references Abteilung (Abkuerzung); ```

SQL Constraint names

If we have query for creating table like this..
create table if not exists food
(
id int not null auto_increment,
user_id int,
name varchar(30),
constraint pk_food primary key(id,name),
foreign key(user_id) references userss(id)
);
What does pk_food mean in this example? I know this is a constraint name, but for what we should be give a name for constraint, if its working without?
create table if not exists food
(
id int not null auto_increment,
user_id int,
name varchar(30),
primary key (id, name),
foreign key (user_id) references userss(id)
);
I mean.. how to use these names and for what we need it?
You gives constraints names for basically two reasons:
You can better understand the error message when the constraint is violated.
You can more easily find the constraint if you want to delete it.

Problem in creating new table ORA-00906: missing left parenthesis

Here is my instruction :
it works on my friend computer !
CREATE TABLE typeRdv1(
id_type int PRIMARY KEY,
des VARCHAR(20)
);
CREATE TABLE rdv1(
id_rdv int PRIMARY KEY,
cin_pat VARCHAR(20),
date_rdv VARCHAR NOT NULL,
type_rdv VARCHAR(20),
state VARCHAR(20),
CONSTRAINT `FK_cin_rdv` FOREIGN KEY (cin_pat)
REFERENCES patients(cin_pat) ON DELETE NO ACTION,
CONSTRAINT `FK_id_type_rdv` FOREIGN KEY (type_rdv)
REFERENCES typeRdv1(id_type) ON DELETE NO ACTION
);
A ORA-00906: missing left parenthesis
Any help !
Please make sure all the "varchar" fields has a length defined. In your second table, it says: date_rdv VARCHAR NOT NULL, which I believe causing the issue, so try to change it into date_rdv VARCHAR(50) NOT NULL and try again.
...
CREATE TABLE rdv1(
id_rdv int PRIMARY KEY,
cin_pat VARCHAR(20),
date_rdv VARCHAR(50) NOT NULL, --length added to varchar
type_rdv VARCHAR(20),
state VARCHAR(20),
...
EDIT:
The reason you get "invalid character" error is that you cannot use "on delete no action" while creating a table with a constraint. Instead you should alter your table after to create your constraints with "on delete cascade" option. Probably like below ( you may need to drop your constraints first):
CREATE TABLE patients(
cin_pat int PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE typeRdv1(
id_type int PRIMARY KEY,
des VARCHAR(20)
);
CREATE TABLE rdv1(
id_rdv int PRIMARY KEY,
cin_pat VARCHAR(20),
date_rdv VARCHAR(50) NOT NULL,
type_rdv VARCHAR(20),
state VARCHAR(20)
);
alter table rdv1 add (
CONSTRAINT FK_cin_rdv FOREIGN KEY (cin_pat)
REFERENCES patients (cin_pat) ON DELETE cascade,
CONSTRAINT FK_id_type_rdv FOREIGN KEY (type_rdv)
REFERENCES typeRdv1 (id_type) ON DELETE cascade
);
Check this for more details: https://www.haidongji.com/2006/07/24/defining-no-action-foreign-key-constraints-in-oracle/comment-page-1/

CONSTRAINT to foreign keys to one table - causes error

I am starting to build something like system up to the just cooperate with suggestions coming into the database called ForslagOpslag.
Every time I try to update table with likes, you will see it with this one error:
Update cannot proceed due to validation errors. Please correct the following errors and try again.
SQL71516 :: The referenced table '[dbo].[ForslagOpslag]' contains no
primary or candidate keys that match the referencing column list in
the foreign key. If the referenced column is a computed column, it
should be persisted.
Here is how I built my ForslagOpslagLikes table:
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_ToGetid]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id]),
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslag]([fk_brugerid])
);
Reason I have both fk_brugerid and getid is for sure me that the user can not vote / like more once!
The way I have built my ForslagOpslag table:
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR (MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
like this to be my like system do:
ForslagOpslagLikes -> fk_brugerid to ForslagOpslag -> fk_brugerid
ForslagOpslagLikes -> getid to ForslagOpslag -> id
Well - the error seems pretty clear: you're trying to estabslish a foreign key relationship to ForslagOpslag.fk_brugerid here:
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslag]([fk_brugerid])
but that column is NOT the primary key of that other table - and it's not a UNIQUE constraint either - so you cannot reference that column in a foreign key relationship.
But the column(s) that a foreign key references must be the primary key of that other table - or in SQL Server, it's good enough if there's a UNIQUE constraint on that column. You must ensure that the values you reference in FroslagOpslag only match a single column in that table - otherwise, you cannot establish a foreign key relationship
Try to remove the foreing key in your first table like this
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_ToGetid]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id]),
);
Then you need to add the foreign key in the second table with the primary key with the first table
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR (MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslagLikes]([fk_brugerid])
);
You sound scandinavian, and Bruger means User (for all the non-scandinavians here).
What you appear to want is a Bruger (User) table, where fk_brugerid in ForslagOpslag is the user who created the record with opretdato being the creation date, and ForslagOpslagLikes is an association table of users who likes the ForslagOpslag with opretdato being the date they clicked on "Like".
CREATE TABLE [dbo].[Bruger]
(
[brugerid] INT IDENTITY (1, 1) NOT NULL,
...,
CONSTRAINT [PK_Bruger]
PRIMARY KEY CLUSTERED ([brugerid])
);
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR(MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
CONSTRAINT [PK_ForslagOpslag]
PRIMARY KEY CLUSTERED ([Id]),
CONSTRAINT [FK_ForslagOpslag_Bruger]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[Bruger] ([brugerid])
);
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_Bruger]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[Bruger] ([brugerid]),
CONSTRAINT [FK_ForslagOpslagLikes_ForslagOpslag]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id])
);

SQL - Missing right parenthesis

I am trying to execute this script in Oracle 11g and getting the following error, I dont know where I am missing the paranthesis or what is the mistake kindly help me figure this out.
Script:
CREATE TABLE User_Role (
user_role_id INT NOT NULL ,
Users_user_id INT FOREIGN KEY REFERENCES Users(user_id),
User_Types_user_type VARCHAR(20) FOREIGN KEY REFERENCES User_Types(user_type),
PRIMARY KEY(user_role_id)
)
Error:
ORA-00907: missing right parenthesi
Delete FOREIGN KEY clause. Rewrite your CREATE TABLE statement as follows:
CREATE TABLE User_Role (
user_role_id INT NOT NULL ,
Users_user_id INT REFERENCES Users(user_id),
User_Types_user_type VARCHAR(20) REFERENCES User_Types(user_type),
PRIMARY KEY(user_role_id)
)
In this case constraint names will be generated by Oracle. If you want to give them more meaningful names you could write your create table statement as follows:
CREATE TABLE User_Role1 (
user_role_id INT NOT NULL ,
Users_user_id INT ,
User_Types_user_type VARCHAR(20) ,
constraint PK_YourTable PRIMARY KEY(user_role_id),
constraint FK_Table_1 foreign key(Users_user_id) REFERENCES Users(user_id),
constraint FK_Table_2 foreign key(User_Types_user_type) REFERENCES User_Types(user_type)
)
I think you need to define the columns first and then add the FOREIGN KEY constraint in the very same manner as you are adding PRIMARY KEY constraint as below:
CREATE TABLE User_Role (
user_role_id INT NOT NULL ,
Users_user_id INT,
User_Types_user_type VARCHAR(20),
FOREIGN KEY (Users_user_id) REFERENCES Users(user_id),
FOREIGN KEY (User_Types_user_type) REFERENCES User_Types(user_type),
PRIMARY KEY(user_role_id)
)
You can specify foreign keys inline, you just need to remove the foreign key keyword:
CREATE TABLE User_Role
(
user_role_id INT NOT NULL ,
Users_user_id INT REFERENCES Users,
User_Types_user_type VARCHAR(20) REFERENCES User_Types,
PRIMARY KEY(user_role_id)
);
SQLFiddle example: http://sqlfiddle.com/#!4/4ca9f/1
Listing the primary key columns in the "references" part is optional. If you prefer, you can also write REFERENCES Users(user_id)
This format also has the disadvantage that the constraint names will be generated by Oracle (with a meaningless name). In order to be able to properly specify a constraint name for the foreign key, you need to use the syntax in the accepted answer.
remove the size of int and recompile
Example :-
integer (20) not null
integer not null
User_Types_user_type VARCHAR(20),
User_Types_user_type VARCHAR,