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;
4
  • Are you using InnoDB sir? Commented Apr 2, 2013 at 7:07
  • As MySQL is one of the very few DBMS to not support check constraints, your only chance is using a trigger. Commented Apr 2, 2013 at 7:07
  • 1
    @BlackHatShadow Yep, forgot to mention, sorry Commented Apr 2, 2013 at 7:11
  • Its ok. try my answer. I don't know the full specs of your table but that might help. Commented Apr 2, 2013 at 7:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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: dev.mysql.com/doc/refman/5.6/en/create-table.html
Also, your solution doesn't work for double values, only for integers. But thanks anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.