tags:

views:

53

answers:

3

I'm making a SQL database with MySQL.

I need a column that has only 3 possible values: "Total" "Hours" "OnDemmand". I mean that user has to select one of these three values, he will can't select another value.

How can I do it?

+8  A: 

See the ENUM type. http://dev.mysql.com/doc/refman/5.0/en/enum.html

i.e.

CREATE TABLE sizes (
    name ENUM('small', 'medium', 'large')
);
Fosco
Note: it's still possible to have an empty value instead of the given three.
Lekensteyn
ohh nice! thx..... but...¿how can i create a enum colum with these values on MySQL Workbench (mysql administrator 2010)?
AndroidUser99
@Fosco - Just being curious, I don't know mysql, what I have to do If I want to add one more possible value to the column, is it possible to alter the column?
johnbk
@johnbk Yes you can alter it like any other column. Of course you may have an issue if removing a value that is currently used.
Fosco
A: 

In Oracle, you can create a check constraint for the column like this -

ALTER TABLE yourtable
add CONSTRAINT yourcolumn
   CHECK (yourcolumn IN ('Total', 'Hours', 'OnDemand'));

There should be equivalent checks incase you are using other database.

johnbk
A: 

If you want to build it into the table itself you would need to use a check constraint, like so:

CREATE TABLE YourTable
(
  YourColumn VARCHAR(50) NOT NULL,
  CONSTRAINT ck_YourConstraint CHECK (YourColumn = 'Total' OR YourColumn = 'Hours' OR YourColumn = 'OnDemand')
)

However, you may want to look into normalizing your database design a step further and putting those into a separate lookup table that your application uses. This will allow you great flexibility in the future in the event that those lookups are modified in any way.

JasonA
CHECK CONSTRAINT is allowed syntax in MySQL but is ignored by it. "The CHECK clause is parsed but ignored by all storage engines." from http://dev.mysql.com/doc/refman/5.1/en/create-table.html
Adrian Smith