In any object oriented programming language ENUM is frequently used "user defined datatype" (UDD), but not every RDBMS databases support ENUM.
MySQL supports ENUM data-type. Let's see how it behaves in the context of MySQL.-- Step1. create table with ENUM datatype
-- 1a. drop table if already exists
DROP TABLE IF EXISTS delete_enum_datatype;
-- 1b. Create table with default values (1. large, 2. small, 3. x-large)
CREATE TABLE delete_enum_datatype (fittings ENUM('large', 'small', 'x-large'))
-- Step2. Insert some Dummy data (already defined in DDL: 'large', 'small', 'Small' with capital S \
-- not in table definition: 'big'
INSERT INTO delete_enum_datatype(fittings) VALUES ('large'), ('big'), ('small'), ('Small')
Point To Ponder: MySql internally stores the key of the ENUM values as integer data-types.
It initialize the key (integer) to the "values" in the order in which we define our values at the time of table creation.
In this case we defined the "fittings" column data-type in the order ('large', 'small', 'x-large','Small')
So MySQL internally associate key in this way
1:large
2:small
3:x-large
2: Small (because we already defined 'small', and MySQL stored all ENUM values in small letters
, so it associate the key "2" to this value which is already defined)
-- How to access the ENUM data-type
MySQL provides us two way to select the ENUM data-typed column values
Let's say we want to select the values from table where "fittings" is 'small', 'large'
1. SELECT * FROM delete_enum_datatype WHERE fittings IN (1,2)
2. SELECT * FROM delete_enum_datatype WHERE fittings IN ('large', 'small')
both of these queries will give you same result-set.
NOTE:
1. If you're inserting any ENUM data which are not defined during table creation, MySQL will put the empty string and the corresponding Key value will be 0
SELECT * FROM delete_enum_datatype WHERE fittings = 'big'
or
SELECT * FROM delete_enum_datatype WHERE fittings = 0
2. MySql will store the ENUM data in small letters (based on your database settings) irrespective of the value being passed in the insert statement.
Let's say you're inserting a record for small in the following ways ('Small', 'SMaLL', 'smALl'). Each of these values will get stored in small letters only.
Comments
Post a Comment