2

Can I define a constraint on a numeric MySQL-column (InnoDB) to only allow values in a certain range?

For example column wavelength in this table:

CREATE TABLE spectrumdata
(
  valueid INT AUTO_INCREMENT,
  spectrumset INT NOT NULL,
  wavelength DOUBLE NULL,
  intensity DOUBLE NULL,
  error INT NOT NULL,
  status INT NOT NULL,
  PRIMARY KEY (valueid),
  INDEX spectrumset_idx (spectrumset),
  CONSTRAINT spectrumset_fk FOREIGN KEY (spectrumset)
    REFERENCES spectrumsets (setid)
)
COLLATE=utf8_general_ci
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=1;
waanders
  • 8,907
  • 22
  • 70
  • 102

1 Answers1

1

If you are using InnoDB as Engine sir, you can check this out. As you can see, you can create a new table that contains your limiting values and reference to your field (as Foreign Key) it is now then enforce your constraint with referencial integrity.

UPDATE

try this:

   CREATE TABLE allowed_val(
      limiting_val DOUBLE NOT NULL,
      PRIMARY KEY (limiting_val )
    ) ENGINE = InnoDB;

INSERT INTO allowed_val( limiting_val) VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),..(1000);

ALTER TABLE spectrumdata
ADD FOREIGN KEY (wavelength) REFERENCES allowed_val(limiting_val);

But you must also alter the spectrumdata wavelength to NOT NULL to DEFAULT = 0; to handle null values.

Community
  • 1
  • 1
Mark
  • 8,046
  • 15
  • 48
  • 78
  • Thanks. But this is a workaround, I was wondering if there's a way forcing it by data definition statements, but it seems there isn't. I found the `CHECK` clause, but the documentation says: "The CHECK clause is parsed but ignored by all storage engines". See: http://dev.mysql.com/doc/refman/5.6/en/create-table.html – waanders Apr 02 '13 at 08:58
  • Also, your solution doesn't work for double values, only for integers. But thanks anyway – waanders Apr 02 '13 at 09:00