How do you use enums in Oracle using SQL only? (No PSQL)
In MySQL you can do:
CREATE TABLE sizes ( name ENUM('small', 'medium', 'large') );
What would be a similar way to do this in Oracle?
You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: “permanent”, “temp”, “apprentice”), or flags (“execute now”, “defer execution”).
An ENUM is a string object with a value chosen from a list of permitted values that are enumerated explicitly in the column specification at table creation time. See Section 11.3. 1, “String Data Type Syntax” for ENUM type syntax and length limits.
To insert data into an ENUM column, you use the enumeration values in the predefined list. For example, the following statement inserts a new row into the tickets table. In this example, instead of using the Low enumeration value, we used value 1. Since Low is mapped to 1, it is acceptable.
Every enum constant is always implicitly public static final. Since it is static, we can access it by using the enum Name. Since it is final, we can't create child enums. We can declare the main() method inside the enum.
Reading a bit about the MySQL enum, I'm guessing the closest equivalent would be a simple check constraint
CREATE TABLE sizes ( name VARCHAR2(10) CHECK( name IN ('small','medium','large') ) );
but that doesn't allow you to reference the value by the index. A more complicated foreign key relationship would also be possible
CREATE TABLE valid_names ( name_id NUMBER PRIMARY KEY, name_str VARCHAR2(10) ); INSERT INTO valid_sizes VALUES( 1, 'small' ); INSERT INTO valid_sizes VALUES( 2, 'medium' ); INSERT INTO valid_sizes VALUES( 3, 'large' ); CREATE TABLE sizes ( name_id NUMBER REFERENCES valid_names( name_id ) ); CREATE VIEW vw_sizes AS SELECT a.name_id name, <<other columns from the sizes table>> FROM valid_sizes a, sizes b WHERE a.name_id = b.name_id
As long as you operate through the view, it would seem that your could replicate the functionality reasonably well.
Now, if you admit PL/SQL solutions, you can create custom object types that could include logic to limit the set of values they can hold and to have methods to get the IDs and to get the values, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With