In the realm of SQL, enumerations, or enums, are a handy data type, especially when you need to restrict input to a list of predefined values. Today, we're going to explore SQL enums, their usage, and how to create and manipulate them. But first, let's understand why we use enums.

Enums come in handy when you want to impose data constraints, like allowing only specific gender options ('Male', 'Female', 'Prefer not to say') in a user registration form. They ensure data consistency and can make your queries more readable and efficient. Now, let's dive into SQL enum in a modern context.

Creating Enums in SQL
Enums are not natively supported in standard SQL. However, many SQL distributions, like PostgreSQL, MySQL, and SQL Server, offer their versions of enums. For this guide, we'll use PostgreSQL's implementation, which is quite comprehensive.

To create an enum in PostgreSQL, you can use the `CREATE TYPE` command followed by the enum name and its possible values, like so:
```sql CREATE TYPE gender AS ENUM ('Male', 'Female', 'Prefer not to say'); ```
Enum Usage in Table Creation

Having created our enum, we can now use it in a table to restrict the valid inputs for our 'gender' column:
```sql CREATE TABLE users ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, gender gender NOT NULL ); ```
Enum Usage in Queries
Enums aren't just about restricting input; they can also make your queries more readable and efficient. Using our enum, the SQL query to fetch users who prefer not to say their gender would look like this:

```sql SELECT * FROM users WHERE gender = 'Prefer not to say'; ```
Enum Functions and Operators
PostgreSQL offers various built-in functions and operators to work with enums. For instance, you can retrieve all possible enum values using the `enum_range()` function:
```sql SELECT enum_range(NULL::gender); ```
Enum functions can also handle value comparisons (`WHEN`, `THEN`), making your queries even more readable:

```sql SELECT CASE gender WHEN 'Male' THEN 'He' WHEN 'Female' THEN 'She' ELSE 'They' END AS pronoun FROM users; ```
Enum Inheritance
One notable feature of PostgreSQL enums is inheritance. You can create a new enum from an existing one, inheriting all its attributes, and extend it with additional values:



















```sql CREATE TYPE us_citizenship UNDER gender AS ENUM ('US Citizen', 'Permanent Resident'); ```
Enum Checking and Casting
You can check if a value belongs to an enum using the `WHEN DISTINCT` clause in a `CASE` expression. Or, you can cast a string to an enum, which will throw an error if the string isn't a valid enum value:
```sql SELECT CASE WHEN 'Unknown'::TEXT WHEN DISTINCT gender THEN 'Invalid gender' END FROM users; ```
In many modern applications, enums can significantly improve code readability and data integrity. They're not just for old-fashioned systems; they're for any system that needs data consistency. Now that you've seen the power of SQL enums, give them a try in your next project!