0

How do I make a constraint in a table for a field (CHAR(20)) that it may only accept, for example, "car" or "bike".

CREATE TABLE Things (
id INTEGER NOT NULL,
thing CHAR(30) NOT NULL,
PRIMARY KEY (id),
CONSTRAINT thingcheck CHECK (thing = "car" OR thing = "bike")
);

If I insert (1, "laptop") it still inserts! Any ideas?

Thanks very much for your time.

--- EDIT ---

As John pointed out, MySQL ignored CHECK clauses. Thanks!

jn1kk
  • 5,012
  • 2
  • 45
  • 72

3 Answers3

3

how about:

ENUM('car', 'bike')
voldomazta
  • 1,300
  • 1
  • 10
  • 19
0

You could create a table that contains a list of the allowed values, and then set up a FOREIGN KEY constraint against it. But, really, why not just use an ENUM?

Ilmari Karonen
  • 49,047
  • 9
  • 93
  • 153
0

How about this,

CREATE TABLE Things (
id INTEGER NOT NULL,
thing CHAR(30) NOT NULL CHECK (thing = 'car' or thing='bike'),
PRIMARY KEY (id),
);

You should give the strings in single quote !!

Jithu
  • 511
  • 4
  • 11
  • 26
  • The quotes don't matter (except in [`ANSI_QUOTES` mode](http://dev.mysql.com/doc/refman/5.6/en/server-sql-mode.html#sqlmode_ansi_quotes)), and [`CHECK` still does nothing](http://stackoverflow.com/questions/2115497/check-constraint-in-mysql-not-working). – Ilmari Karonen Oct 11 '11 at 06:08