Question

In order to create a FOREIGN KEY Constraint, the <AuthorizationID> that owns the referencing Table must be the current <AuthorizationID> and must have the REFERENCES Privilege on every referenced Column named. Source: https://mariadb.com/kb/en/constraint_type-foreign-key-constraint/

WHY?

Was it helpful?

Solution

The reason for the references privilege is that the table referencing another imposes a constraint on the other table, and the owner of that other table may not be willing to allow that constraint.

Let's see what could happen if there was no references privilege.

CREATE TABLE Employees
(
    EmpID   INTEGER NOT NULL PRIMARY KEY,
    Name    VARCHAR(32) NOT NULL,
    …
);

INSERT INTO Employees VALUES (1, "Hernandez", …);

Now along comes Joe and creates a table:

CREATE TABLE EmployeeRefs
(
    EmpID INTEGER NOT NULL PRIMARY KEY REFERENCES Employees
);

INSERT INTO EmployeeRefs SELECT EmpID FROM Employees;

Now suppose that the HR department needs to let Hernandez go and work elsewhere, and the code knows that the relevant EmpID is 1:

DELETE FROM Employees WHERE EmpID = 1;

This delete fails; the primary key value is still being referenced from the EmployeeRefs table.

This is what is supposed to happen as far as the DBMS is concerned. It was told that values in the EmployeeRefs.EmpID column must match a value in the Employee.EmpID column, and if it deletes Hernandez's record, that won't be true, so it must prevent the deletion (since Joe didn't set up a cascading delete).

Clearly, if any user (with privilege to create tables in the DB) can prevent the HR department from doing its work, there is a problem. The problem is resolved by saying that Joe can only create the reference to the Employee table if he has been given the REFERENCES privilege. And the owner/creator of each table gets to choose who has REFERENCES privilege for the tables that they create.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top