HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Making a column immutable in MySQL

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
makingmysqlimmutablecolumn

Problem

I want to make a column in a relation unmodifyable for consistency reasons.

The backstory is that I have a n:n relationship where the "connecting" relation has additional values. I don't want that anyone is able to change the IDs of the relationship partners.

What I have come up with so far:

Creating a trigger that checks if the NEW value is the same as the OLD value. But I don't know how to deny the UPDATE action if the condition proves as TRUE.

Here is my trigger so far:

CREATE TRIGGER deny_nton_change BEFORE UPDATE ON Schueler_in_Klasse
FOR EACH ROW BEGIN
    IF NEW.Schueler_ID != OLD.Schueler_ID OR NEW.Klasse_ID != OLD.Klasse_ID THEN

    END IF;
END;

Solution

A fairly nice and clean way to abort and return a readable error message is by using a signal:

SIGNAL sqlstate '45000' SET message_text = 'Schueler_ID and Klasse_ID may not be altered!';

Do make sure your MySQL version supports this, it was introduced in MySQL 5.5. In earlier versions you need hacks like inserting a non existant field into a non existant table.

As gbn mentions, overwriting the new values with the old ones is a good option too.

Context

StackExchange Database Administrators Q#8360, answer score: 4

Revisions (0)

No revisions yet.