how to delete relationship between two tables? - sql

I created two tables How to delete relationship between them in sql code;
Course table:
create table course
(
course_id int primary key identity (1,1),
course_name varchar(40)
);
Employee table:
create table employee
(
emp_id int identity(1,1) primary key,
fname varchar(30),
course_id int
foreign key references course (course_id)
);

If this is for SQL Server - then you can find out the name of the FK constraint using this statement:
SELECT name
FROM sys.foreign_keys
WHERE parent_object_id = OBJECT_ID('employee')
AND referenced_object_id = OBJECT_ID('course')
and once you have that FK constraint name, you can use the usual
ALTER TABLE dbo.employee DROP CONSTRAINT (name of the FK constraint)
This will be an arbitrary, system-generated name (something like FK__employee__cours__7EB7AD3A or similar) - and this is the reason I'd recommend to always explicitly name your constraints - like this:
create table employee
(
emp_id int identity(1,1) primary key,
fname varchar(30),
course_id int
constraint fk_employee_course
foreign key references course (course_id)
);
Now, you know what the name of that FK constraint is - you named it fk_employee_course. This is also beneficial if you get any error messages about FK constraint violations - if that name is intuitive and obvious, then you'll know what went wrong

Related

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.

Can I use one same primary key in two different tables?

'''
CREATE TABLE Employee
(
employeeID INT (10) PRIMARY KEY,
Name CHAR (20)
);
'''
'''
CREATE TABLE SALARY
(
employeeID INT (10) PRIMARY KEY,
Salary INT (10)
);
'''
Is it possible to use the same primary key in both tables?
Yes. You can have same column name as primary key in multiple tables.
Column names should be unique within a table. A table can have only one primary key, as it defines the Entity integrity.
If this question is about data modelling parent-child relationship, There are two types. You are read more on this.
Identifying relationship : Child identifies itself by the help of parent. Here, Employee & Salary will share the same primary key. Primary key of parent table (EmployeeId) will be primary key of child table also (Salary).
Non-Identifying relationship: Child is having its own identity. Here, Employee & Salary will have different primary key. Child table will have its own primary key(say SalaryId) and will have primary key of parent as a Foreign key(EmployeeId).
If your question is if you can use the same EMPLOYEEID column as the primary ID on multiple tables, the answer is "YES, YOU CAN"
You can use the same column as primary index on multiple tables, but you cannot have more than one primary index on a table
Yes, you can. You would make salary.employeeid both the table's primary key and a foreign key to the employee table:
CREATE TABLE salary
(
employeeid INT (10) NOT NULL,
salary INT (10) NOT NULL,
CONSTRAINT pk_salary PRIMARY KEY (employeeid,
CONSTRAINT fk_salary_employeeid FOREIGN KEY (employeeid) REFERENCES employee (employeeid)
);
This creates a {1}:{0,1} relationship between the tables and ensures that you cannot store a salary without having stored the employee and that you cannot store more than one salary for one employee.
This is something we rarely do. (We would rather make the salary a column in the employee table.) The only advantage of a separate salary table I see is that you can grant rights on the employee table but revoke them on the salary table, so as to make the salary table invisible to some database users.
You can do this, however, it is bad design.
I would suggest having the EmployeeId as the PK on the employee table and the EmployeeId as a Foreign Key on the Salary table, with the Salary table having it's own PK (most likely SalaryId).
Also the field [Name] I would personally steer clear of too, as "Name" is a reserved word in SQL.
CREATE TABLE dbo.Employee
(
EmployeeId BIGINT IDENTITY(1,1)
,EmployeeName VARCHAR(20) NOT NULL
,CONSTRAINT PK_Emp PRIMARY KEY (EmployeeId)
);
GO
CREATE TABLE dbo.Salary
(
SalaryId BIGINT IDENTITY(1,1)
,EmployeeId BIGINT NOT NULL
,Salary INT NOT NULL
,CONSTRAINT PK_Sal PRIMARY KEY (SalaryId)
,CONSTRAINT FK_EmpSal FOREIGN KEY (EmployeeId)
REFERENCES Employee(EmployeeId)
);
GO
All of that said, I think a little more thought into the db structure you should most likely end up with 3 tables. It is likely that many staff will have the same salary, lets say 5 employees are on 40,000 and 3 are on 50,000, etc.
You will end up storing the same Salary value multiple times.
A better way is to store that value once and have a third table that links an employee with a salary (in this case I have called it [Earnings]).
With this structure the salary of say 40,000 is stored 1 time in the db and you can link an employeeId to it multiple times.
CREATE TABLE dbo.Employee
(
Id BIGINT IDENTITY(1,1)
,EmployeeName VARCHAR(20) NOT NULL
,CONSTRAINT PK_Emp PRIMARY KEY (Id)
);
GO
CREATE TABLE dbo.Salary
(
Id BIGINT IDENTITY(1,1)
,Salary INT NOT NULL
,CONSTRAINT PK_Sal PRIMARY KEY (Id)
);
GO
CREATE TABLE dbo.Earnings
(
Id BIGINT IDENTITY(1,1)
,EmployeeId BIGINT NOT NULL
,SalaryId BIGINT NOT NULL
,CONSTRAINT PK_Ear PRIMARY KEY (Id)
,CONSTRAINT FK_EmpEar FOREIGN KEY (EmployeeId)
REFERENCES Employee(Id)
,CONSTRAINT FK_SalEar FOREIGN KEY (SalaryId)
REFERENCES Salary(Id)
);
GO
Technically, it is possible.
However, it is advisable to use Foreign key. This will:
-Avoid redundancy
-Help in maintaining db structure
-Improve readability
For this example, use:
CREATE TABLE Employee ( EmployeeID INT PRIMARY KEY, Name CHAR (20), Primary Key (EmployeeId) );
CREATE TABLE SALARY ( SalaryId INT , EmployeeID INT , Salary INT (10), Primary Key (SalaryId), Foreign Key (EmployeeId) REFERENCES Employee );
*An even better approach would be to add a constraint instead of just mentioning
[key names]
Like:
CREATE TABLE Employee(
EmployeeId INT,
Name CHAR(20)
)
ALTER TABLE Employee ADD CONSTRAINT PK_EmployeeId PRIMARY KEY
Can do by differents ways
I have a "Main" table named "Peoples" with "peopleId" as PK Identity
"Child" tables
"PeopleDocs" with "peopleId" PK
"PeopleImages" with "peopleId" PK
"PeopleKeys" with "peopleId" PK.
So, when i create one
record on "Peoples" i populate the "childs" with empty records to work
later.
This logic is about a federal law on my country and some people
informations has a life cicle and must be deleted if the life cicle
ends or the owner of the data demands. So we split the people
sensitive data on child tables to not lose all bussiness records,
refferences and log about that people.
Col1 as Primary key on both tables
SELECT
P.COL1,
P.COL2,
C.COL2,
C.COL3
FROM
TBL1 P, TBL2 C
WHERE
C.COL1 = P.COL1
Or using joins
SELECT
P.COL1,
P.COL2,
C.COL2,
C.COL3
FROM
TBL1 AS P
INNER JOIN
TBL2 AS C
ON
C.COL1 = P.COL1

Prevent multiple foreign key references to same row in primary table

I have a table containing Employees all of whom have an ID; I'm referencing this ID in two other tables (Salesman, Mechanic) via a foreign key. What I want to ensure is that an employee is either a mechanic or a salesman, but never both. In other words, I want to associate this logic with my foreign keys:
How would I integrate logic like that into a table? I'm a SQL beginner, so I apologize if this is a dumb question.
These are my tables:
CREATE TABLE [dbo].[Employee]
(
Number INT NOT NULL,
-- ...
PRIMARY KEY(Number)
);
CREATE TABLE [dbo].[Salesman]
(
ID INT NOT NULL,
-- ...
PRIMARY KEY(ID),
FOREIGN KEY(ID) REFERENCES [dbo].[Employee](ID)
);
CREATE TABLE [dbo].[Mechanic]
(
ID INT NOT NULL,
-- ...
PRIMARY KEY(ID),
FOREIGN KEY(ID) REFERENCES [dbo].[Employee](ID)
);
This is a one-of relationship and it is tricky to implement in SQL. Here is one method:
CREATE TABLE [dbo].[Employee] (
EmployeeId INT PRIMARY KEY,
EmployeeType VARCHAR(32)
-- ...
CHECK (EmployeeType IN ('Mechanic', 'SalesPerson')),
UNIQUE (EmployeeType, EmployeeId)
);
CREATE TABLE [dbo].[SalesPerson]
(
EmployeeId INT PRIMAY KEY,
-- ...
EmployeeType as (CONVERT(VARCHAR(32), 'Salesperson')) PERSISTED,
FOREIGN KEY (EmployeeType, EmployeeId) REFERENCES [dbo].[Employee](EmployeeType, EmployeeId)
);
CREATE TABLE [dbo].[Mechanic] (
EmployeeId INT PRIMARY KEY,
EmployeeType as (CONVERT(VARCHAR(32), 'Mechanic')) PERSISTED,
-- ...
FOREIGN KEY (EmployeeType, EmployeeId) REFERENCES [dbo].[Employee](EmployeeType, EmployeeId)
);
Here is a SQL Fiddle illustrating the code.

Foreign key in the first table

I have a question about foreign keys.
How does it work when I want to add a foreign key to the first table that I make that references to the primary key of the second table I create?
CREATE TABLE table1
(
name_id INT NOT NULL,
team TEXT REFERENCES table2(team_id),
PRIMARY KEY(name_id)
);
CREATE TABLE table2
(
team_id INT NOT NULL,
teamname TEXT,
PRIMARY KEY(team_id)
);
If I try the code above I get the following error:
ERROR: relation "" does not exist
Thanks in advance.
Either create the second table first. Or use alter table. That is, create the first table without the reference and then do:
alter table table1 add constraint fk_table1_team
foreign key (team_id) REFERENCES table2(team_id);
The declaration for table1 would be:
CREATE TABLE table1 (
name_id INT NOT NULL,
team_id INT,
PRIMARY KEY(name_id)
);
The reference between the tables should be on the primary key and certainly not on a character column, if an integer is available.
here's the syntax of creating a table with Foreign key:
CREATE TABLE table11
(
name_id INT NOT NULL,
team INT,
PRIMARY KEY(name_id),
foreign key(team) references table22(team_id)
);
CREATE TABLE table22
(
team_id INT NOT NULL,
teamname TEXT,
PRIMARY KEY(team_id)
);
but there was another problem. a foreign key from a child table cannot reference to a primary key from a parent folder if they do not contain the same type. in your code team was of TEXT and team_id was of INT which cannot be.

How to implement bidirectional referenced tables?

I have a table School and a table Teacher having a one-to-many relationship. However, one of the teachers is the school's principle, and only one teacher can be the school principle. So I thought of saving the teachers id (principle) in the School table as follows:
CREATE TABLE School (
ID INT PRIMARY KEY,
Name VARCHAR(40),
PrincipleID INT FOREIGN KEY REFERENCES Teacher.ID
)
CREATE TABLE Teacher (
ID INT PRIMARY KEY,
Name VARCHAR(40),
SchoolID INT FOREIGN KEY REFERENCES School.ID
)
I know I could loose the foreign key reference in the school table, but that's not an option.
Should I make the reference after the table creation? If yes, how?
Another solution is to create a new table, let's say SchoolsPrinciples with just two fields:
CREATE TABLE SchoolsPrinciples
(
SchoolId int,
TeacherId int,
CONSTRAINT uc_SchoolTeacher UNIQUE (SchoolId, TeacherId)
)
A UNIQUE constraint let you obtain exactly one teacher per each school.
When building the tables, you'll need to add the constraint as a separate alter statement. Note also that when creating foreign keys, you should only specify the table name, not the referenced column (the column is implied by the primary key).
CREATE TABLE School (
ID INT PRIMARY KEY,
Name VARCHAR(40),
PrincipleID INT);
CREATE TABLE Teacher (
ID INT PRIMARY KEY,
Name VARCHAR(40),
SchoolID INT
CONSTRAINT FK_Teacher_School
FOREIGN KEY REFERENCES School);
ALTER TABLE School add
CONSTRAINT FK_School_Teacher
FOREIGN KEY (PrincipleID) REFERENCES Teacher;
When you add data, you'll need to set the PrincipleID field as a separate update:
insert into School (ID, Name)
values (1, 'Blarg Elementary');
insert into Teacher (ID, Name, SchoolID)
values (1, 'John Doe', 1),
(2, 'Bob Smith', 1),
(3, 'Adam Walker', 1);
update School set PrincipleID = 2 where ID = 1;
Put a boolean IsPrincipal on the Teacher table instead. Or add a third relationship table
CREATE TABLE SchoolPrincipals (
INT SchoolID PRIMARY KEY FOREIGN KEY REFERENCES School.ID,
INT TeacherID FOREIGN KEY REFERENCES Teacher.ID
)
Keeps everything tidy without painful delete logic.
You can take a column in Teacher table as
IsPrincipal where only one row will have value as true as referred
by jonnyGold,
This can be checked by triggers.
OR
You can use filtered index if using Sql Server 2008.
Create unique filtered index where SchoolID, IsPrincipal
is NOT NULL and are unique
Boss where this will contain ID of principal hence creating employee manager relationship which in your case is not suitable.
CREATE TABLE EmpManager
(
TeacherID int
SchoolID int
IsPrincipal bit
)
And use filtered index or trigger to handle the scenario.
EDIT:
CREATE TABLE [dbo].[Teacher](
[ID] [int] NOT NULL primary key,
[Name] [varchar](40) NULL,
[SchoolID] [int] NULL,
)
GO
CREATE TABLE [dbo].[School](
[ID] [int] NOT NULL primary key,
[Name] [varchar](40) NULL,
[PrincipleID] [int] NULL,
)
GO
ALTER TABLE [dbo].[Teacher] WITH CHECK ADD CONSTRAINT [FK_Teacher_School] FOREIGN KEY([SchoolID])
REFERENCES [dbo].[School] ([ID])
GO
ALTER TABLE [dbo].[School] WITH CHECK ADD CONSTRAINT [FK_School_Teacher] FOREIGN KEY([PrincipleID])
REFERENCES [dbo].[Teacher] ([ID])
GO
Better design should be the one suggested by ADC