dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Using ENUM to Pre-define Column Values in MySQL

Learn how the values for a particular column can be pre-defined during the table definition. These values will be validated when the records are inserted or updated in the table.


advertisement

You may choose to validate the data that you enter in a table, either at the database level or at the application level.

Application level is feasible only if the source of data is the application. Many instances are present in which the data can be directly uploaded to the database from a script that will be time-saving.

MySQL supports ENUM and using the values for a particular column can be pre-defined during the table definition and this will be validated when the records are inserted or updated in the table.

Example:

CREATE TABLE GRADES (
    NAME VARCHAR(40),
    GRADE ENUM('A', 'B', 'C', 'D', 'E')
);

and now using the pre-defined values of the ENUM for column GRADE which can take values as defined.

Correct SQL:

INSERT INTO GRADES (NAME, GRADE) VALUES 
		('STUDENT 1', 'B'), 
		('STUDENT 2', 'A'), 
		('STUDENT 3', 'A'),
		('STUDENT 4', 'B');

Incorrect SQL:

INSERT INTO GRADES (NAME, GRADE) VALUES 
		('STUDENT 5', 'G');

 

Visit the DevX Tip Bank

 



   
Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date